def Extract_frame(): print("Choose video file....") fname = askopenfilename(initialdir = '/home/andyc/Videos/') print("where do you want to save?(choose folder)\n") savepath = askdirectory(initialdir = '/home/andyc/image/') while savepath == '': print("wrong folder!!\n") print("where do you want to save?(choose folder)\n") savepath = askdirectory(initialdir = '/home/andyc/image/') savepath = savepath+'/' video = cv2.VideoCapture(fname) if video.isOpened(): rval,frame = video.read() else: rval = False idx = 0 while rval: print("Extracting {0} frame".format(idx)) rval,frame = video.read() name = savepath+str(idx).zfill(6)+'.jpg' if rval: cv2.imwrite(name,frame) idx = idx+1 video.release() return savepath
def main(): root=Tk() root.withdraw() #Get rid of visible default TK base window newPath = tkFileDialog.askdirectory(initialdir='/', title='Select NEW VSDX Documents Folder') oldPath = tkFileDialog.askdirectory(initialdir='/', title='Select OLD VSDX Documents Folder') destPath = tkFileDialog.askdirectory(initialdir='/', title='Select Comparison Results Folder') oldFiles = getOldFiles(oldPath) newFiles = getNewFiles(newPath) # Open report.txt file rptFilename = destPath + '/' + 'ComparisonReport_' + str(date.today()) + '.txt' with open(rptFilename, 'w') as rptFile: rptFile.write('Comparison Report for %s\n\n' % str(date.today())) rptFile.write('Total OLD Files: %d\n' % len(oldFiles)) rptFile.write('Total NEW Files: %d\n\n' % len(newFiles)) # Compare the files for newFile in newFiles: if newFile in oldFiles: compareFiles(oldPath, newPath, destPath, newFile) else: rptFile.write('New file added: %s\n' % newFile) rptFile.write('\n\n') for oldFile in oldFiles: if oldFile not in newFiles: rptFile.write('Old file dropped: %s\n' % oldFile)
def getPath(): root = Tk() root.withdraw() InputPath = askdirectory(title="Choose Converting Picture Input Path") OutputPath = askdirectory(title="Choose Converting Picture Output Path") root.destroy() return InputPath, OutputPath
def getMayaDir(self): if self.plateform == "darwin": dir=self.sharedDirectory+"/Autodesk/maya/2011/plug-ins/" if not os.path.exists(dir): x = askdirectory(initialdir=self.progDirectory, title="where is MAYA2011 plugin directory") dir = x self.dir[3].set(dir) self.softdir[3] = dir elif self.plateform == "win32": dir=self.findDirectoryFrom("Maya2011",self.progDirectory+os.sep+"Autodesk"+os.sep) if len(dir) ==0 : x = askdirectory(initialdir=self.progDirectory, title="where is MAYA2011 bin/plugins directory") dir = x self.dir[3].set(dir) self.softdir[3] = dir elif len(dir) == 1 : dir = dir[0] dir = dir +os.sep+"bin"+os.sep+"plug-ins" self.dir[3].set(dir) self.softdir[3] = dir else : self.chooseDirectory(3,dir) elif self.automaticSearch and dir is None: dir=self.findDirectory("maya2011",self.rootDirectory) dir = dir.replace(" ","\ ") self.dir[3].set(dir) self.softdir[3] = dir
def askdirectory(self): """Returns a selected directoryname.""" print(tkFileDialog.askdirectory(**self.dir_opt)) return tkFileDialog.askdirectory(**self.dir_opt)
def getPaths(): global pathFirst global pathSecond root = tk.Tk() root.withdraw() pathFirst = tkfd.askdirectory(title="Select First Folder Path") pathSecond = tkfd.askdirectory(title="Select Second Folder Path")
def askdirectory(self,button_name): #gets the directory name if button_name=='proj': self.dirname_data.set(tkFileDialog.askdirectory()) elif button_name=='beam': self.dirname_lf.set(tkFileDialog.askdirectory()) elif button_name=='dark': self.dirname_dc.set(tkFileDialog.askdirectory())
def gettemplate(self): if os.path.exists(self.templatepath): l = tkFileDialog.askdirectory(initialdir=self.templatepath, mustexist=True) else: l = tkFileDialog.askdirectory(mustexist=True) if os.path.exists(l): self.templatepath = l self.entryboxes['Template'].delete(0,END) self.entryboxes['Template'].insert(0, self.templatepath)
def getlocation(self): if os.path.exists(self.location): l = tkFileDialog.askdirectory(initialdir=self.location, mustexist=True) else: l = tkFileDialog.askdirectory(mustexist=True) if os.path.exists(l): self.location = l self.entryboxes['Location'].delete(0,END) self.entryboxes['Location'].insert(0, self.location)
def _ask_path_to_directory(self): """ Ask a path to the destination directory. If a dir has been already specified, open the choice window showing this dir. """ if not self.homeDir: path = askdirectory(**_DialogueLabels.save_output_directory_choice) else: path = askdirectory(initialdir = self.homeDir, **_DialogueLabels.save_output_directory_choice) if path: self.homeDir = path return path
def getDir(initialDir=""): root = tk.Tk() root.withdraw() if(initialDir != ""): file_path = tkFileDialog.askdirectory(initialdir=initialDir) else: file_path = tkFileDialog.askdirectory() root.destroy() return file_path
def extracter(spreadsheet, column_name): """ The extracter moves files. Arguments input_folder and output_folder are set through GUI. Based on the values in the column called column_name in the spreadsheet, files are copied from input_folder to output_folder. Here, these are the gilbert_numbers in the spreadsheet fed from main(). The are matched to the file names. Each gilber_number gets its own directory in the output_folder. output_folder should be empty, at least not contain the same gilbert_numbers already. Also copies all speaker files from input_folder to output_folder. """ print header, "Running the extracter." root=Tkinter.Tk() root.withdraw() root.update() input_folder=tkFileDialog.askdirectory(title="Inputfolder: Please choose a directory that contains your corpus files") root=Tkinter.Tk() root.withdraw() root.update() output_folder=tkFileDialog.askdirectory(title="Outputfolder: Please choose a directory to copy files into") print header, "Copying files from '{}' to '{}'.".format(input_folder, output_folder) #collecting input files inputfiles=[] print "Locating files." for dirpath, subdirs, files in os.walk(input_folder): for f in files: inputfiles.append(os.path.join(dirpath, f)) if len(inputfiles) in [1000,2000,4000,8000,1600,24000]: print "{} files processed, still working.".format(len(inputfiles)) print "Found {} files.".format(len(inputfiles)) #read from spreadsheet # with open(spreadsheet, "r") as spreadsheet: # spreadsheet=pandas.read_csv(spreadsheet, encoding="utf-8") numbers_to_be_extracted= spreadsheet[column_name].unique() print header, "Gilbert numbers to be extracted:" print ",".join([unicode(i) for i in numbers_to_be_extracted]) #copying speaker files print header, "Copying speaker files." speakerfiles=[f for f in inputfiles if re.match(".*\.txt", os.path.split(f)[1])] os.mkdir(os.path.join(output_folder, "speakers")) for s in speakerfiles: shutil.copy2(s, os.path.join(output_folder, "speakers")) #finding relevant input files result=[] for number in numbers_to_be_extracted: print "Processing {}, creating folder '{}'.".format(number, number) os.mkdir(os.path.join(output_folder, unicode(number))) regex="(\d+)-(\d+)-(\d+)-"+number.astype('U')+"-(\D+)\.wav" findings= [f for f in inputfiles if re.match(regex, os.path.split(f)[1])] result= result+findings for find in findings: shutil.copy2(find, os.path.join(output_folder, unicode(number), os.path.split(find)[1])) print header, "{} files have been copied to {}.".format(len(result), output_folder)
def AskDirectory(self, title='Choose Directory', initialdir="."): """Run pop-up menu for user to select directory.""" # This is not an error # pylint: disable=E1101 if sys.version_info < (3,): dirname = tkFileDialog.askdirectory(parent=self.master, initialdir=initialdir,title=title) else: dirname = tkFileDialog.askdirectory(parent=self.master, initialdir=initialdir,title=title) return dirname # <-- string
def ExpBrowse(): if not self.hasBrowsed: dir = tkFileDialog.askdirectory(title='Choose a directory', initialdir=self.initBrowseDir) self.hasBrowsed = True else: dir = tkFileDialog.askdirectory(title='Choose a directory') if not dir: return None #self.addExp_Entry.setvalue(dir) self.AddExperiment(dir)
def getFolders(self): self.input_dir = tkFileDialog.askdirectory( parent=self.parent, title="Please select an input directory for 2dx_automator" ) if len(self.input_dir) == 0: raise SystemExit("No input directory selected") self.output_dir = tkFileDialog.askdirectory( parent=self.parent, title="Please select an output directory for 2dx_automator" ) if len(self.output_dir) == 0: raise SystemExit("No output directory selected")
def getFolders(self): self.input_dir = tkFileDialog.askdirectory(parent=self.parent, title="Input directory for movies from the DED camera, e.g. /run/user/1001/gvfs/ftp:host=192.168.210.1.port=8021/...") if len(self.input_dir)==0: raise SystemExit("No input directory selected") self.output_dir = tkFileDialog.askdirectory(parent=self.parent, title="Output directory for averages and other files, e.g. /mnt/cina-qnap01/.../DC_averages") if len(self.output_dir)==0: raise SystemExit("No averages output directory selected") stack_dir = tkFileDialog.askdirectory(parent=self.parent, title="Output directory for aligned stacks, e.g. /mnt/cina-qnap01/.../DC_stacks") if len(stack_dir)==0: raise SystemExit("No stack-output directory selected") self.export_location_stack = stack_dir
def pathOpen(option=0): if option is 0: userpath.set(tkFileDialog.askdirectory(parent=root)) cfg.userPath = userpath.get() elif option is 1: gtpath.set(tkFileDialog.askdirectory(parent=root)) if os.path.isfile(os.path.join(gtpath.get(), "data.mat")): cfg.gtPath = gtpath.get() cfg.loadGT() tempo.set(cfg.tempo) duration.set(cfg.duration) else: tkMessageBox.showinfo("ERROR", "Missing data file. Please choose a different folder.")
def askInstallPrefix(self): """ command for search button """ initDir=self.installP.get() newPrefix="" if os.path.exists(initDir): newPrefix=tkFileDialog.askdirectory(parent=self,initialdir=initDir,mustexist=1) else: newPrefix=tkFileDialog.askdirectory(parent=self,mustexist=1) if newPrefix: self.installP.delete(0, Tkinter.END) self.installP.insert(0, newPrefix)
def __init__(self): """Constructor""" self.workspace = arcpy.env.workspace = tkFileDialog.askdirectory(initialdir = INITDIR, parent=tkRoot, title = 'Choose workspace (ArcPy)', mustexist = True) arcpy.env.scratchWorkspace = tkFileDialog.askdirectory(initialdir = INITDIR+"\scratchworkspace", parent=tkRoot, title = 'Choose scratch workspace (ArcPy)', mustexist = True) #Arcpy specific arcpy.CheckOutExtension("spatial") #Load sa license arcpy.env.overwriteOutput = True #Enable overwrite existing data arcpy.env.outputCoordinateSystem = OUTPUT_COORDINATESYSTEM #"Coordinate Systems/Projected Coordinate Systems/UTM/WGS 1984/Northern Hemisphere/WGS 1984 UTM Zone 43N.prj" self.pArcPyTools = ArcPyTools() #Init of own tool class
def file_select(self, file_type): #file_type is internal, uses string ints (goes in order of layout in __init__ if file_type == '0': #this is bwa_directory self.bwa_directory_path.config(state = NORMAL) self.bwa_directory_path.delete(1.0, END) file_name = tkfd.askdirectory(parent=self, title='Select BWA Aligner directory') self.bwa_directory_path.insert(INSERT, file_name) self.bwa_directory_path.config(state = DISABLED) with open('paths.txt', 'r') as file: lines = file.readlines() lines[0] = file_name + '\n' with open('paths.txt', 'w') as file: file.writelines(lines) elif file_type=='1': #this is picard_directory self.picard_directory_path.config(state = NORMAL) self.picard_directory_path.delete(1.0, END) file_name = tkfd.askdirectory(parent=self, title='Select Picard Tools directory') self.picard_directory_path.insert(INSERT, file_name) self.picard_directory_path.config(state = DISABLED) with open('paths.txt', 'r') as file: lines = file.readlines() lines[1] = file_name + '\n' with open('paths.txt', 'w') as file: file.writelines(lines) elif file_type=='2': #this is samtools_directory self.samtools_directory_path.config(state = NORMAL) self.samtools_directory_path.delete(1.0, END) file_name = tkfd.askdirectory(parent=self, title='Select SamTools directory') self.samtools_directory_path.insert(INSERT, file_name) self.samtools_directory_path.config(state = DISABLED) with open('paths.txt', 'r') as file: lines = file.readlines() lines[2] = file_name + '\n' with open('paths.txt', 'w') as file: file.writelines(lines) else: #this is the output directoyr self.out_dir_path.config(state = NORMAL) self.out_dir_path.delete(1.0, END) file_name = tkfd.askdirectory(parent=self, title='Select output directory') self.out_dir_path.insert(INSERT, file_name) self.out_dir_path.config(state = DISABLED)
def find_directory(self): folder_path = tkFileDialog.askdirectory(**self.dir_opt) while not self.is_a_vivaldi_folder(folder_path): if self.user_close_window(folder_path): sys.exit(1) tkMessageBox.showerror("Error searching Vivaldi folder","That isn\'t a Vivaldi folder") self.dir_opt['initialdir'] = folder_path folder_path = tkFileDialog.askdirectory(**self.dir_opt) return folder_path
def tkGUI(): root = tk.Tk(); root.title('Stratec pQCT File Scrubber') tk.Label (root, text ="Scrub sensitive patient/participant info from Stratec pQCT files", font=("Helvetica", 18, "bold"), ).pack(pady=5, padx=10, anchor=tkcnst.W) tk.Label (root, text ="* Replace date of birth with the 1st of nearest month\n"+ "* Zero-out patient name field", font=("Helvetica", 16), justify=tkcnst.LEFT, ).pack(pady=10, padx=10, anchor=tkcnst.W) step_label = tk.StringVar() step_label.set ("\nStep 1: Select folder with Stratec files\n") tk.Label (root, textvariable = step_label, font=("Helvetica", 16, "bold"), justify=tkcnst.LEFT, ).pack(pady=10, padx=10, anchor=tkcnst.W) dir_in = tkfd.askdirectory(mustexist=True,title="Select folder with Stratec files") if not dir_in: quit() step_label.set ("\nStep 2: Select folder for scrubbed Stratec files\n") dir_out = tkfd.askdirectory(mustexist=False,title="Select folder for scrubbed files") if not dir_out: sys.exit(0) step_label.set ("\n'"+dir_in+"' -> '"+dir_out+"'\n") # update here to get the current size of root root.update() progressbar = ttk.Progressbar (orient=tkcnst.HORIZONTAL, length=root.winfo_reqwidth()-40, mode='determinate') progressbar["value"] = 0 progressbar.pack() but_frame = tk.Frame(root) exit_button = tk.Button(but_frame, text="Quit", command=quit) exit_button.pack(pady=10, padx=10, side=tkcnst.LEFT) log_button = tk.Button(but_frame, text="View Log", command=view_log) log_button.pack(pady=10, padx=10, side=tkcnst.LEFT) but_frame.pack(side=tkcnst.BOTTOM, anchor=tkcnst.W) # Register an idle task to process the files idle_task_tk (root, progressbar, process_files (dir_in, dir_out)) root.mainloop()
def browse_for_folder(e): """Pull up a folder browsing dialog and dump the resulting path into the Tkinter.Entry widget e.""" path = tkFileDialog.askdirectory() if (path != ""): # Unless they hit cancel. e.delete(0, END) e.insert(0, path)
def ask_base_dir(self): """Selects Baseline Report Folder and Prints it""" vars.base_dir = tkFileDialog.askdirectory(title="Please Select Baseline Report Directory", initialdir = vars.config.get('Kludge','base_dir'), mustexist = "False") vars.base_dir = vars.base_dir.replace("/","\\") self.base_dir_path.set(vars.base_dir) self.conf_save('base_dir', vars.base_dir) print ("Baseline Directory " + vars.base_dir)
def outPathBrowse(self): """ Use the askdirectory tk dialog to get output path. """ self.outPath = tkFileDialog.askdirectory() if self.outPath: self.outPath = self.outPath.replace('/', '\\') self.outEntry.delete(0, tk.END) self.outEntry.insert(0, self.outPath)
def askdirectory(self): """Returns a selected directoryname.""" self.dirname = tkFileDialog.askdirectory(**self.dir_opt) self.entryVariable.set(self.dirname) self.buttonView.configure(state=NORMAL) return self.dirname
def btnOutput(self): x = tkFileDialog.askdirectory( mustexist = True, title = "Select Output Folder", initialdir = self.outputVar.get()) if x: self.outputVar.set(x)
def LoadFolder(): global index global photo global photolist global filenames global factor,scalevalue scalevalue=100 dirname="" photolist = [] filenames = [] filetypes = ['*.jpg','*.png','*.gif','*.bmp'] dirname=tkFileDialog.askdirectory(title='Select a directory') dirname=dirname.replace("\\","/") dirname=dirname.replace("[","\[") dirname=dirname.replace("]","\]") dirname=dirname.replace("\[","[[]") dirname=dirname.replace("\]","[]]") if dirname=="": showwarning("Load Error","You haven't selected a folder") else: for type in filetypes: files = glob.glob(dirname+"//"+type) for name in files: name=name.replace("\\","/") filenames.append(name) index = 0 factor = 1 NextTen()
def load_dir(): the_dir = tkFileDialog.askdirectory(title=load_dir_text) if is_label: label = os.path.basename(the_dir) else: label = None file_list.add_entry_label(the_dir, label)
def main(): root = tk.Tk() root.withdraw() rootDir = tkFileDialog.askdirectory() + '\\' bpDir = '\\Calibration\\BitePlate\\' palDir = '\\Calibration\\Palate\\' rawDir = '\\Kinematic\\Raw\\' corDir = '\\Kinematic\\Corrected\\' folds = os.listdir(rootDir) num = '0', '1', '2', '3', '4', '5' osCol = 86 msCol = 95 decPrec = 4 for f in folds: if f.startswith(num): print "Processing " + f + "..." subFold = rootDir + f + bpDir bpfiles = [fn for fn in glob.glob(subFold+'/*biteplate*.tsv') if "_BPC" not in fn] bpfile = bpfiles[-1] # Uses the "last" BP file (in the event of something like bpfile_2.tsv) indir = rootDir + f + rawDir outdir = rootDir + f + corDir files = glob.glob(indir+'/*.tsv') OS, rot = bpUtils.BiteplateUtils.getRotation(bpfile, osCol, msCol) processFiles(OS, rot, indir, outdir, decPrec, files) # Now do the palate traces indir = rootDir + f + palDir outdir = indir files = [fn for fn in glob.glob(indir+'/*.tsv') if "_BPC" not in fn] processFiles(OS, rot, indir, outdir, decPrec, files) print f + " done."
def browse(self, widget): LOG.debug("MainDialog::browse...") # Tix.DirSelectDialog is deprecated, thus use tk_chooseDirectory d = tkFileDialog.askdirectory() # cannot use control variables as the target entry_field is in widget self.entry_settext(widget, d)
def dialogSelectOutDir(self): self.outdir = tkFD.askdirectory(initialdir="/", title="Select output directory") self.updateInfo()
''' Utility to create a video from a directory of images ''' import os import sys import cv2 import Tkinter import tkFileDialog import tkMessageBox Tkinter.Tk().withdraw() sourceDir = tkFileDialog.askdirectory() destDir = sourceDir + '/' + 'results' try: os.mkdir(destDir) except OSError as e: if e.errno == 17: if tkMessageBox.askokcancel( 'Folder already exists', 'The output folder already exists, proceeding may overwrite the files it contains.' ): pass else: print('Exiting ImageBlender') sys.exit(1) fileNames = [ sourceDir + '/' + str(f) for f in os.listdir(sourceDir) if f.endswith('.JPG') or f.endswith('.jpg') ]
def askDir(self): dirname = filedialog.askdirectory() self.dir_name.set(dirname) self.loadDir(dirname)
def browse(self): dirname = askdirectory() self.mnt.set(dirname) self.ent_mnt.delete(0,tk.END) self.ent_mnt.insert(0,dirname)
#print '\n'.join(OrigPosixPaths) if args.skipOffline is False: if args.basic: ListOfofflineFiles = doesPathExist(OrigPosixPaths) else: ListOfofflineFiles = doesPathExist(DecompPosixPaths) prettySep() ####save reports print "Check your dock for the python spaceship. Select the folder which will house the reports." root = Tkinter.Tk() root.withdraw() dirname = tkFileDialog.askdirectory( parent=root, initialdir='~/Desktop/', title='A time-stamped subfolder will be created at this location.') if len(dirname) > 0: filepaths_ParserReportsDir = dirname + '/' + 'JRAIM_LOGS/FILEPATH_PARSER_REPORTS/' + parsedFilename + timeStampDaFucker( ) + '/' #print filepaths_ParserReportsDir else: print 'Exiting.' exit() os.makedirs(filepaths_ParserReportsDir) print "Writing data to text files...." initialAssessmentFile = '%s/ListOfFiles_initialAssessment%s.txt' % ( filepaths_ParserReportsDir, timeStampDaFucker()) BrokenApartFile = '%s/ListOfFiles_BrokenApart%s.txt' % (
def getFolderPath(titletext="Please select a folder"): return tkFileDialog.askdirectory(title=titletext)
Button(master, text='Enter', command=take).grid(row=17, column=1, sticky=W, pady=4) master.mainloop() #extracting the number of folders from the list, this is just a quirk of Tkinter numfolds = numfoldlist[0] #ask user where exiftool.exe is located. This is neccessary for using the exiftool module. root = Tkinter.Tk() currdir = os.getcwd() # current working directory exiftoolloc = str( tkFileDialog.askdirectory( parent=root, initialdir=currdir, title='Please select the directory where exiftool.exe is located')) #empty list for image directories and save directories. There will be the same number of each that corresponds to the number of folders. origimgdirs = [] savedirs = [] #For every folder user selects image directory of images to be corrected and save directory h = 1 while h <= numfolds: root = Tkinter.Tk() currdir = os.getcwd() # current working directory orig_img_dir = str( tkFileDialog.askdirectory( parent=root, initialdir=currdir,
def open_output_directory_dialog(self): filename = tkfd.askdirectory(initialdir=self.initialdir, title="Select directory") if filename != '': self.initialdir = filename self.output_dirname_var.set(filename)
def browseDirectory(self): self.targetDir = tkFileDialog.askdirectory() self.loadFiles()
def load_several_html(cls, text, root): proc_log = [] if askyesno(u"Загрузить папку", u"Загрузить новую папку?"): dir_name = askdirectory() print dir_name filenames_set = os.listdir(dir_name) #filenames_set = askopenfilenames() print filenames_set text.config(state='normal') text.delete("1.0", "end") text.insert("end", u"В обработке...\n") text.config(state='disabled') if filenames_set == []: text.config(state='normal') text.delete("1.0", "end") text.insert("end", u"Пожалуйста, выберите файлы.\n") text.config(state='disabled') else: if not os.path.exists(dir_name + '/transliterated/'): os.mkdir(dir_name + '/transliterated/') if not os.path.exists(dir_name + '/log/'): os.mkdir(dir_name + '/log/') if not os.path.exists(dir_name + '/passed/'): os.mkdir(dir_name + '/passed/') passed_files = [] spelling = 1 # SPELLING for curr_filename in filenames_set: # print 'CURRENT FILE', curr_filename if cls.check_transliterated(curr_filename, dir_name): # print 'IS CHECKED' META['filename'] = curr_filename ##print meta.filename name = os.path.splitext( os.path.basename(META['filename']))[0] ##print meta.res if META['filename'] == '': text.config(state='normal') text.delete("1.0", "end") text.insert("end", u"Пожалуйста, выберите файлы.\n") text.config(state='disabled') else: try: temp_filename = cls.get_temp_in_dir(dir_name) # print 'START ITERATE' proc_log.append('START') new_text, log_data, wrong_log = cls.iterate_root( temp_filename, root, 0) # print 'STOP ITERATE' proc_log.append('STOP') suffix = os.path.splitext(META['filename'])[1] META[ 'result_name'] = dir_name + '/transliterated/' + name + suffix with codecs.open(META['result_name'], 'w') as inf: inf.write(new_text) log_name = dir_name + '/log/' + name + '_log.txt' wrong_changes = [] # print 'CREATE LOG NAME' if log_data: print 'IS LOG DATA' log_data = u'\n'.join(log_data) log_data = log_data.split(u'\n') # print 'LD' check_log = [ h.split(u' --> ')[1] for h in log_data ] # print '-->' raw_log_forms = [ h.replace(u']', u'').replace(u'[', u'') for h in check_log ] # wrong_changes = [] print 'RAW LOG' if len(raw_log_forms) < 22000: check_log_forms = [ u' '.join(raw_log_forms) ] print 'CREATE LOG FORMS' else: check_log_forms = [] tmp_clf = [] for o, uu in enumerate(raw_log_forms): if o != 0 and not o % 22000: check_log_forms.append( u' '.join(tmp_clf)) tmp_clf = [] tmp_clf.append(uu) if tmp_clf: check_log_forms.append( u' '.join(tmp_clf)) with codecs.open('log_forms', 'w', 'utf-8') as chlf: chlf.write(u'\n'.join(check_log_forms)) print 'CHECK LOG' if spelling: print 'SPELLING' spelled_raw = [] for chlf in check_log_forms: print 'PART LOG' cmd = "echo " + chlf + " | hunspell -d ru_Ru" p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable="/bin/bash") spelled, err_sp = p.communicate() spelled_parts = spelled.decode( 'utf-8').split('\n')[1:][:-2] spelled_raw += spelled_parts print 'SPELLED ALL PARTS' # with codecs.open('spell_test.txt', 'w', 'utf-8') as spw: # spw.write(u'\n'.join(spelled)) # with codecs.open('log_test_2.txt', 'w', 'utf-8') as ss: # ss.write(u'\n'.join(log_data)) # for j, sp in enumerate(spelled): # if sp[0] == u'&': # print j, sp, u'=', log_data[j] # wrong_changes.append(log_data[j]) # log_data[j] = log_data[j] + u' *' # print 'DECODED SPELLED' spelled = [] for s in spelled_raw: if s.strip() != u'': spelled.append(s) # print 'GET SPELLED LIST' gap = 0 num_gap = 0 for j, sp in enumerate(log_data): prev_pos = j + gap - num_gap # if j == 31: # pass # print 'IM IN', j, sp, gap # print 'DATA', j + gap, len(spelled) curr_word = sp.split(u' --> ')[1] # if curr_word == u'Дон-Кихоте': # pass if re.search( u'^[0-9\-]+$', curr_word): num_gap += 1 continue if j + gap - num_gap >= len( spelled): break # print 'NOW SPELL' # print 'THIS', j + gap - num_gap, spelled[j + gap - num_gap] # print u'%%%%'.join(spelled[686:690]) if spelled[j + gap - num_gap][0] == u'&': print j, spelled[ j + gap - num_gap], u'=', log_data[j] spell_ans = u' '.join( spelled[j + gap - num_gap].split( u':') [0].split(u' ')[1:-2]) # wrong_changes.append(log_data[j]) wrong_changes.append(spell_ans) log_data[ j] = log_data[j] + u' *' # print 'NOW HYP' if u' ' in curr_word: curr_arr_space = curr_word.split( u' ') gap += len( re.findall( u' ', curr_word)) else: curr_arr_space = [curr_word] curr_arr = [] for m, curr_p in enumerate( curr_arr_space): if u'-' in curr_p: gap += len( re.findall( u'-', curr_p)) curr_p = curr_p.split(u'-') if curr_p == [u'', u'']: gap -= 1 continue for cwp in curr_p: if re.search( u'^[0-9]+$', cwp ) or cwp == u'': gap -= 1 if cwp != u'': curr_arr.append( cwp) else: curr_arr.append(curr_p) # print 'CHECK -' new_curr_arr = [] for m, curr_p in enumerate( curr_arr): if re.search(u'[0-9]', curr_p): # new_curr_arr = [] # for cwp in curr_arr: tmp_cwp = re.split( u'[0-9]+', curr_p) if tmp_cwp[0] == u'': tmp_cwp = tmp_cwp[1:] if tmp_cwp and tmp_cwp[ -1] == u'': tmp_cwp = tmp_cwp[:-1] if tmp_cwp: new_curr_arr += tmp_cwp if len(new_curr_arr) > len( curr_arr): num_gap += len( new_curr_arr ) - len(curr_arr) else: new_curr_arr.append(curr_p) # print 'CHECK NUM' if j + gap - num_gap > prev_pos: # print 'IS DIFF' # diff = j + gap - num_gap - prev_pos try_pos = 1 while prev_pos + try_pos < j + gap - num_gap + 1: if spelled[prev_pos + try_pos][ 0] == u'&': # print j, spelled[prev_pos + try_pos], u'=', log_data[j] wrong_changes.append( log_data[j]) log_data[j] = log_data[ j] + u' *' break try_pos += 1 # print 'CHECK DIFF' print 'SPELLED' with codecs.open(log_name, 'w', 'utf-8') as logf: logf.write(u'\n'.join(log_data)) # logf.write(log_data) print 'SAVE LOG' wrong_log_name = dir_name + '/log/' + name + '_err_spelled.txt' with codecs.open(wrong_log_name, 'w', 'utf-8') as wrf: wrf.write(u'\n'.join(wrong_changes)) print 'SAVE WRONG' except: #print 'PASSED', meta.filename if proc_log[-1] == 'STOP': try: with codecs.open( 'err_in_spell', 'a', 'utf-8') as eis: eis.write(META['filename']) eis.write(u'\n') except: try: with codecs.open( 'err_in_spell', 'a', 'utf-8') as eis: eis.write( META['filename'].decode( 'utf-8')) eis.write(u'\n') except: pass elif proc_log[-1] == 'START': try: with codecs.open( 'err_in_struct', 'a', 'utf-8') as eis: eis.write(META['filename']) eis.write(u'\n') except: try: with codecs.open( 'err_in_struct', 'a', 'utf-8') as eis: eis.write( META['filename'].decode( 'utf-8')) eis.write(u'\n') except: pass passed_files.append(META['filename']) else: # passed_files.append(META['filename']) print 'DIDNT CHECKED' passed_files.append(curr_filename) text.config(state='normal') text.delete('1.0', 'end') text.insert('end', u'\nВыполнено\n') text.configure(cursor='arrow') text.config(state='disabled') SaveText.save_passed(passed_files, dir_name)
def get_sdir(self): subject_directory = tkFileDialog.askdirectory() self.sdir_label_text.set(subject_directory)
def click_save(self): filename = filedialog.askdirectory(initialdir='~/') self.save_path.config(text=filename)
mat_answer = scipy.io.loadmat(filename_path) answer_sheet = mat_answer['answer_sheet'] # load data_matrix from each recording site # for each file # divided to 2 parts (80% training, 20% testing) # do this for n times # each time 80% used to train SVM # test this SVM on the 20% data # output the accuracy each time and calculate average file_path = os.path.dirname(os.path.realpath(__file__)) root = Tkinter.Tk() root.withdraw() dirname = tkFileDialog.askdirectory(parent=root, initialdir=file_path, title='Please select a directory') filename_list = [] # path to save all jj of 100 classifilers jj_path = 'C:\\Users\\mz86\\Desktop\\fNIRS ML\\trained_classifiers\\100_exp1_MNN' # for jj times repeat train 100 classifier on each recording site. for jj in range(0, 1): # for this jj save trained 100 clasifier at jj_path_each = jj_path + '\\' + str(jj) # repeat this whole process k times # to aclculate the averrage accuracy
def button_setrecdir(self): path = tkFileDialog.askdirectory( initialdir=".", title='Select directory for recosnstructions') self.e[5].delete(0, Tkinter.END) self.e[5].insert(0, path)
else: zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file)) except Exception, e: print(" Error adding {}: {}".format(file, e)) return None try: root = Tkinter.Tk() root.withdraw() root.attributes('-topmost', True) getGDBLoc = tkFileDialog.askdirectory( parent=root, initialdir="C:", title='Select the folder which contains the GDBs to be zipped') root.attributes('-topmost', False) wkPath = os.path.abspath(getGDBLoc).replace("\\", "/") root.destroy() # Create the zip file for writing compressed data. In some rare instances, the ZIP_DEFLATED constant may be unavailable and the # ZIP_STORED constant is used instead. When ZIP_STORED is used, the zip file does not contain compressed data, resulting in large zip files. for fldr in os.listdir(wkPath): if fldr.endswith('.gdb'): outfile = fldr + ".zip" try: zip = zipfile.ZipFile(os.path.join(wkPath, outfile), 'w', zipfile.ZIP_DEFLATED) zipws(os.path.join(wkPath, fldr), zip, False) zip.close()
def open_kml_server_preview_directory_dialog(self): filename = tkfd.askdirectory(initialdir=self.initialdir, title="Select directory") if filename != '': self.initialdir = filename self.kml_server_preview_directory_var.set(filename)
def dirnameDialog_text(self, text): fl = tkFileDialog.askdirectory(initialdir=text.get()) if fl != '': self.reset_entry(text, fl)
def selectgraceformatteddatadir(self): self.formatteddatapath = tkFileDialog.askdirectory( initialdir="/", title="Select GRACE formatted Data Directory") self.inputgracedirtxtfield.delete(1.0, tk.END) self.inputgracedirtxtfield.insert(tk.END, self.formatteddatapath)
def open_photo(self): self.backup_path = self.path.get() path_ = tkFileDialog.askdirectory() self.var_msg.set("Importing images... This may take awhile =) ") self.path.set(path_) print("folder path: %s" % self.path.get()) # handle error when user click 'cancel' button on the import image window if self.path.get() == '': self.var_msg.set("Please select an image folder.") print("Please select an image folder.") self.path.set(self.backup_path) else: self.file_ls = [ ] # image list: [(<Tkinter.Checkbutton instance>,<Tkinter.IntVar instance>),......] self.file_chosen_ls = [ ] # image data list: [<Tkinter.Checkbutton instance>,......] self.datetime_ls = [] self.image = [] self.photo = [] # delete photos on GUI self.frame_in2.destroy() self.frame_in2 = Tk.Frame(self.canvas) # self.canvas.create_window((0, 0), window = self.frame_in2, anchor="center", height="25c", width="15c") # self.frame_in2.grid() self.canvas.create_window((0, 0), window=self.frame_in2, anchor='nw') self.frame_in2.bind("<Configure>", self.my_canvas) # Handle No. of rows of photos based on image frame width no_row = self.get_row() col = 0 row = 0 for file_name in os.listdir(self.path.get()): global image, photo if file_name.endswith(".jpg") or file_name.endswith(".jpeg"): self.image.insert( 0, Image.open(os.path.join( self.path.get(), file_name)).resize((self.image_width, int(self.image_width * 0.75)))) self.photo.insert(0, ImageTk.PhotoImage(self.image[0])) var = Tk.IntVar() c1 = Tk.Checkbutton(self.frame_in2, text=file_name, image=self.photo[0], variable=var, onvalue=1, offvalue=0, width=self.cb_width) c1.grid(row=row, column=col) # c1.pack() col += 1 if col >= no_row: row += 1 col = 0 self.file_ls.append((c1, var)) # handle no image folder if len(self.file_ls) == 0: self.var_msg.set("No jpg or jpeg file in %s." % self.path.get()) else: self.var_msg.set("Imported " + str(len(self.file_ls)) + " images successfully from " + str(self.path.get()) + ".") self.db_name = self.getDbName(self.path.get()) # Create directory if it is not exist if os.path.isdir("../database/data_" + self.db_name) == False: os.mkdir("../database/data_" + self.db_name, 0755) print "Path is created" self.db_link = "../database/data_" + self.db_name + "/" + self.db_name + '.db' with sqlite3.connect(self.db_link) as db: cur = db.cursor() # Create table if it is a new database if db is not None: self.create_table( db, self.sql_create_table ) # only execute this line when db is a new database print("Created a new database: %s" % self.db_name + '.db') self.var_msg.set("Created a new database: %s" % self.db_name + '.db') else: print("Error! cannot create the database connection.") for x in self.file_ls: f = x[0] name = f.cget("text") cur.execute( "SELECT id FROM attributes WHERE file = (?)", (name, )) row = cur.fetchall() # If picture is already recorded in database if len(row) != 0: f.configure(bg="tomato")
normal_samples_gene_expressions[gene_name] = [] for sample_id in gene_expression.get_samples_list(): sample_gene_expression_value = gene_expression.get_gene_exp_matrix_dataframe()[sample_id][gene_name] if gene_expression.get_sample_tissue_types_dict()[sample_id] == constants.SAMPLE_TYPE_TUMOR: tumor_samples_gene_expressions[gene_name].append(sample_gene_expression_value) elif gene_expression.get_sample_tissue_types_dict()[sample_id] == constants.SAMPLE_TYPE_NORMAL: normal_samples_gene_expressions[gene_name].append(sample_gene_expression_value) if float(np.mean(np.array(normal_samples_gene_expressions[gene_name]))) == 0.0: avg_gene_exp_ratio[gene_name] = "n/a" else: avg_gene_exp_ratio[gene_name] = float(np.mean(np.array(tumor_samples_gene_expressions[gene_name]))) / \ float(np.mean(np.array(normal_samples_gene_expressions[gene_name]))) print("\nFinished calculating average gene expression value ratio\n\n") # Write .csv files print("---> Please select the directory to which you want to save the analysis results.gene expression file downloaded from UCSC Xena Browser <---\n\n") save_dir = tkFileDialog.askdirectory() root.update() if save_dir is None: exit() print("Started writing data to .csv files") summary_file = save_dir + "/results/analysis.csv" raw_gene_exp_file = save_dir + "/results/gene_expressions.csv" # Create the files if not os.path.exists(os.path.dirname(summary_file)): try: os.makedirs(os.path.dirname(summary_file)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise if not os.path.exists(os.path.dirname(raw_gene_exp_file)): try:
def file_browse(self): self.dir_name = tkFileDialog.askdirectory( initialdir="/", title='Choose a target directory') pe_name = str(os.path.normpath(self.dir_name)) # print pe_name self.fill_path(str(pe_name))
def dir_open(): dir_path = tkFileDialog.askdirectory() e1.delete(0, END) e1.insert(0, dir_path)
print('Writing processed data to {0}'.format(outfile)) alldat.to_csv(outfile, index=False) pstc_df = get_pstc_data(datadir) pstc_df = pstc_df.astype({"Subject": str, "Session": str}) blink_df = blink_df.astype({"Subject": str, "Session": str}) pstc_df = pd.merge(pstc_df, blink_df, on=['Subject','Session','OddballSession']) pstc_outfile = os.path.join(datadir, 'oddball_group_pstc_' + tstamp + '.png') plot_group_pstc(pstc_df, pstc_outfile) if __name__ == '__main__': if len(sys.argv) == 1: print('USAGE: {} <data directory> '.format(os.path.basename(sys.argv[0]))) print("""Searches for datafiles created by oddball_proc_subject.py for use as input. This includes: <session>-<subject>_SessionData.csv <session>-<subject>_PSTCdata.csv <session>-<subject>_BlinkPct.json <session>-<subject>_GLMresults.json Calculates subject level measures of pupil dilation and contrast to noise ratios. Plots group level PTSC. Output can be used for statistical analysis.""") root = tkinter.Tk() root.withdraw() # Select folder containing all data to process datadir = filedialog.askdirectory(title='Choose directory containing subject data') proc_group(datadir) else: datadir = sys.argv[1] proc_group(datadir)
def SelectFolderDialog(): Tk().withdraw() folder = askdirectory() return folder
def browse_button(entry): filename = tkFileDialog.askdirectory() entry.insert(0, filename)
def chooseDir(self, parent, controller, place_holder, message): current_dir = os.getcwd() parent.update() chosen_dir = tkFileDialog.askdirectory(parent=self, initialdir = current_dir, title='Select the location of ' + message) place_holder.set(chosen_dir)
def output_askdirectory(self): select_dir = tkFileDialog.askdirectory() self.output_directory.set(select_dir) return select_dir
def Execute(self): if self.Image == None: if self.Input == None: self.PrintError('Error: no Image.') self.Image = self.Input extensionFormats = { 'vti': 'vtkxml', 'vtkxml': 'vtkxml', 'vtk': 'vtk', 'mhd': 'meta', 'mha': 'meta', 'tif': 'tiff', 'png': 'png', 'dat': 'pointdata' } if self.OutputFileName == 'BROWSER': import tkFileDialog initialDir = '.' self.OutputFileName = tkFileDialog.asksaveasfilename( title="Output image", initialdir=initialDir) if not self.OutputFileName: self.PrintError('Error: no OutputFileName.') if self.OutputDirectoryName == 'BROWSER': import tkFileDialog initialDir = '.' self.OutputDirectoryName = tkFileDialog.askdirectory( title="Output directory", initialdir=initialDir) if not self.OutputDirectoryName: self.PrintError('Error: no OutputDirectoryName.') if self.GuessFormat and self.OutputFileName and not self.Format: import os.path extension = os.path.splitext(self.OutputFileName)[1] if extension: extension = extension[1:] if extension in extensionFormats.keys(): self.Format = extensionFormats[extension] if self.PixelRepresentation != '': cast = vtk.vtkImageCast() cast.SetInput(self.Image) if self.PixelRepresentation == 'double': cast.SetOutputScalarTypeToDouble() elif self.PixelRepresentation == 'float': cast.SetOutputScalarTypeToFloat() elif self.PixelRepresentation == 'short': cast.SetOutputScalarTypeToShort() else: self.PrintError('Error: unsupported pixel representation ' + self.PixelRepresentation + '.') cast.Update() self.Image = cast.GetOutput() if self.UseITKIO and self.Format not in [ 'vtkxml', 'tiff', 'png', 'dat' ]: self.WriteITKIO() else: if (self.Format == 'vtkxml'): self.WriteVTKXMLImageFile() elif (self.Format == 'vtk'): self.WriteVTKImageFile() elif (self.Format == 'meta'): self.WriteMetaImageFile() elif (self.Format == 'png'): self.WritePNGImageFile() elif (self.Format == 'tiff'): self.WriteTIFFImageFile() elif (self.Format == 'pointdata'): self.WritePointDataImageFile() else: self.PrintError('Error: unsupported format ' + self.Format + '.')
def dialog_for_lecture_path(): classes_dir = rwkos.FindFullPath('siue/classes') outpath = tkFileDialog.askdirectory(initialdir=classes_dir) outpath = force_seps(outpath) return outpath