def init_progress(progress_widget: ttk.Progressbar, max_level: int): '''Initialize a progress bar. Arguments: progress_widget {ttk.Progressbar} -- The progress bar to be initialized. max_level {int} -- The maximum level for the progress bar. ''' progress_widget.configure(maximum=max_level) progress_widget["value"] = 0 progress_widget.update_idletasks()
class ProgressBarScreen(Toplevel): def __init__(self, master): super().__init__(master = master) self.title("Progress Screen") self.geometry("300x150") setWindowStyle(self) self.labelFrame = Frame(self) self.labelFrame.configure(background=window_bg) self.minLabel = createLabel(self.labelFrame) self.maxLabel = createLabel(self.labelFrame) setStyleText(self.minLabel, "0%") setStyleText(self.maxLabel, "100%") self.minLabel.grid(row = 0, column= 0, padx = 20) self.maxLabel.grid(row = 0, column= 4, padx = 20) self.labelFrame.grid(row = 0, column = 1, pady = (40, 0)) self.progressBar = Progressbar(self) self.progressBar.grid(row = 1, column = 1, pady = 5) self.progressLabel = createLabel(self) setStyleText(self.progressLabel, "INITIALIZING...") self.progressLabel.grid(row = 2, column = 1) def updatePercentage(self, percentage, message): if percentage < 98: self.progressBar["value"] = percentage self.progressBar.update_idletasks() self.minLabel["text"] = str(percentage) + "%" self.progressLabel["text"] = message else: global usingMergedData if not usingMergedData: clearSplittedChannelsSelected(0) clearSplittedChannelsSelected(1) else: clearMergedChannelsSelected(0) clearMergedChannelsSelected(1) generate_btn["state"] ="normal" self.destroy()
class InpaintApp(Frame): def __init__(self): super().__init__() self.initInpaintUI() def initInpaintUI(self): self.master.title("Fill Your Face") self.pack(fill=BOTH, expand=True) self.columnconfigure(1, weight=1) self.columnconfigure(4, pad=2) self.rowconfigure(4, weight=1) self.rowconfigure(5, pad=2) lbl = Label(self, text="Please select a mask type & face to fill.") lbl.grid(sticky=W, pady=4, padx=5) wbtn = Button(self, text="Choose Folder", command=self.saveLoc) wbtn.place(x=10, y=30) # variables self.save_loc = None self.chosen_img = None self.completed_img = None self.msk = None self.lr = config.learning_rate self.moment = config.momentum self.nitrs = config.niters self.l2loss = False self.saveEaItr = False # saves images after ea iteration to visualize manifold self.weighted_mask = config.weighted_mask self.show_mskedim = False self.saveMask = IntVar() # checkboxes whether to save as image self.saveMaskedIm = IntVar() # buttons right abtn = Button(self, text="Select Image", command=self.openImg) abtn.grid(row=2, column=4, padx=5, pady=5) abtn = Button(self, text="Random Image", command=self.getRandImg) abtn.grid(row=1, column=4, padx=5, pady=5) # choose mask choices = {'Center', 'Random', 'Half'} self.mask_type = StringVar(root) self.mask_type.set("Select Mask Type") popupMenu = OptionMenu(self, self.mask_type, *choices, command=self.display_mask) popupMenu.grid(row=1, column=3, padx=5) dmbtn = Button(self, text="Display Masked Image", command=self.display_masked_img) dmbtn.grid(row=2, column=3, padx=5) # buttons lower hbtn = Button(self, text="Help", command=self.clickHelp) hbtn.grid(row=5, column=0, padx=5, pady=5) wbtn = Button(self, text="Settings", command=self.setParams) wbtn.grid(row=5, column=1) Button(self, text="Save Image(s)", command=self.saveImg).grid(row=5, column=2, padx=5, pady=5) obtn = Button(self, text="Start Inpaint", command=self.start_inpaint) obtn.grid(row=5, column=3, padx=5, pady=5) cbtn = Button(self, text="Quit", command=self.ExitApplication) cbtn.grid(row=5, column=4, padx=5, pady=5) # progress bar Label(self, text="Inpainting Progress:").place(x=40, y=260) self.progressbar = Progressbar(self, length=500) # self.progressbar.config(mode = 'determinate', maximum=self.nitrs) self.progressbar.place(x=40, y=280) def ExitApplication(self): MsgBox = messagebox.askquestion( 'Exit Application', 'Are you sure you want to exit the application', icon='warning') if MsgBox == 'yes': root.destroy() def openImg(self): filename = filedialog.askopenfilename( ) # show an "Open" dialog box and return the path to the selected file if filename[-4:] == '.png' or filename[-4:] == 'jpeg' or filename[ -4:] == '.jpg': img = Image.open(filename) self.blend_tar = np.asarray(img) # for poisson blending later self.blend_tar.flags.writeable = True if img.size != (64, 64): messagebox.showwarning( "Error", "Please choose a 64x64 rgb face image.\ \n You can use openface to crop your image. Click Help for more info." ) return self.chosen_img = np.asarray(img, dtype="float32") img = img.resize((100, 100), Image.ANTIALIAS) imgtk = ImageTk.PhotoImage(img) txt_lbl = Label(self, text="Your Image") txt_lbl.place(x=50, y=110) dis_img = Label(self, image=imgtk) dis_img.image = imgtk dis_img.place(x=50, y=127) else: messagebox.showwarning("Error", "Please select a png or jpeg image") def getRandImg(self): dataset = tf.data.TFRecordDataset(filenames="data.tfrecord") dataset = dataset.map(func.extract_fn) # dataset = tf.data.TFRecordDataset.from_tensor_slices(dataset) dataset = dataset.shuffle(buffer_size=300) dataset = dataset.batch(1) iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes) init_op = iterator.make_initializer(dataset) # batched data to feed in image_data = iterator.get_next() # visualize original data with tf.Session() as sess: sess.run(init_op) real_img = np.array(sess.run(image_data)) rand_img = real_img[0, :, :, :] self.chosen_img = np.asarray(rand_img, dtype="float32") img = toimage(rand_img) self.blend_tar = np.asarray(img) # for poisson blending later self.blend_tar.flags.writeable = True img = img.resize((100, 100), Image.ANTIALIAS) imgtk = ImageTk.PhotoImage(img) txt_lbl = Label(self, text="Your Image") txt_lbl.place(x=50, y=110) dis_img = Label(self, image=imgtk) dis_img.image = imgtk dis_img.place(x=50, y=127) def saveLoc(self): self.save_loc = filedialog.askdirectory() self.dis_save = Label(self, text='Save Location: ') self.dis_save.place(x=10, y=60) slength = len(self.save_loc) if slength > 40: self.dis_save['text'] += "..." self.dis_save['text'] += self.save_loc[-40:] else: self.dis_save['text'] += self.save_loc def saveImg(self): if self.completed_img is not None: im = toimage(self.completed_img) im = im.resize((250, 250), Image.ANTIALIAS) if self.save_loc is not None: # file = filedialog.asksaveasfile(mode='w', defaultextension=".jpg") uniq_filename = 'CompletedImg_' + str( datetime.datetime.now().time()).replace(':', '.') filename = self.save_loc + '/' + uniq_filename + '.jpg' imageio.imwrite(filename, im) if self.saveMask.get(): uniq_filename = 'Mask_' + str( datetime.datetime.now().time()).replace(':', '.') filename = self.save_loc + '/' + uniq_filename + '.jpg' mskimg = toimage(self.msk) mskimg = mskimg.resize((250, 250), Image.ANTIALIAS) imageio.imwrite(filename, mskimg) if self.saveMaskedIm.get(): uniq_filename = 'MaskedImg_' + str( datetime.datetime.now().time()).replace(':', '.') filename = self.save_loc + '/' + uniq_filename + '.jpg' masked_img = preinpaint.get_masked_image( self.msk, self.chosen_img) masked_img = toimage(masked_img) masked_img = masked_img.resize((250, 250), Image.ANTIALIAS) imageio.imwrite(filename, masked_img) messagebox.showinfo("Success!", "Your image has been saved") else: messagebox.showwarning("Error", "Please choose folder to save image.") else: messagebox.showwarning("Error", "Please inpaint first to get image.") def display_mask(self, mask_type): if mask_type != "Select Mask Type": self.msk = preinpaint.make_mask(mask_type, weighted_mask=self.weighted_mask) # mskimg = Image.fromarray(msk, 'RGB') # dispmsk = preinpaint.make_mask(mask_type, weighted_mask=False) mskimg = toimage(self.msk) mskimg = mskimg.resize((100, 100), Image.ANTIALIAS) imgtk = ImageTk.PhotoImage(mskimg) txt_lbl = Label(self, text="Your Mask: ") txt_lbl.place(x=200, y=110) dis_img = Label(self, image=imgtk) dis_img.image = imgtk dis_img.place(x=200, y=127) else: messagebox.showwarning("Error", "Please select a mask first!") def display_masked_img(self): if self.chosen_img is not None and self.msk is not None: masked_img = preinpaint.get_masked_image(self.msk, self.chosen_img) masked_img = toimage(masked_img) masked_img = masked_img.resize((100, 100), Image.ANTIALIAS) imgtk = ImageTk.PhotoImage(masked_img) txt_lbl = Label(self, text="Masked Image: ") txt_lbl.place(x=350, y=110) dis_img = Label(self, image=imgtk) dis_img.image = imgtk dis_img.place(x=350, y=127) self.show_mskedim = True else: messagebox.showwarning("Error", "Please load image and mask") def start_inpaint(self): l2 = self.l2loss savegenerated = self.saveEaItr if self.chosen_img is not None and self.msk is not None: self.progressbar['value'] = 0 self.progressbar.update_idletasks() img = preinpaint.preprocess(self.chosen_img) # print(img.dtype, np.amax(img), np.amin(img)) # debugging images = preinpaint.single_to_batch(img) masks = preinpaint.single_to_batch(self.msk) # gen_images, loss = inpaint.get_best_z_img(masks, images, iters=self.nitrs) # backprop to z z = np.random.randn(config.BATCH_SIZE, config.z_dim) vel = 0 iters = self.nitrs r = self.lr momentum = self.moment self.progressbar.config(mode='determinate', maximum=self.nitrs) # load frozen graph graph, graph_def = func.loadpb("dcgan-100.pb") g_in = graph.get_tensor_by_name('dcgan/z:0') g_out = graph.get_tensor_by_name('dcgan/Tanh:0') g_loss = graph.get_tensor_by_name('dcgan/Mean_2:0') d_in = graph.get_tensor_by_name('dcgan/real_images:0') d_out = graph.get_tensor_by_name('dcgan/Sigmoid:0') with tf.Session(graph=graph) as sess: # create batches of masks & images to feed in mask_placeholder = tf.placeholder( tf.float32, shape=(config.BATCH_SIZE, config.image_size, config.image_size, config.channels)) # real image batches, use if own image input images_placeholder = tf.placeholder( tf.float32, shape=(config.BATCH_SIZE, config.image_size, config.image_size, config.channels)) inpaint_loss, gradient = inpaint.get_losses( mask_placeholder, images_placeholder, g_in, g_out, g_loss, l2) bests = [] for i in range(iters): # yield Label(self, text="Inpainting Progress:" + str(i)).place(x=40, y=280) feed_dict = { mask_placeholder: masks, images_placeholder: images, g_in: z } loss, grad, gen_images = sess.run( (inpaint_loss, gradient, g_out), feed_dict=feed_dict) grad = grad[0] v_prev = vel vel = v_prev * momentum - r * grad # z += vel z += vel * ( 1 + momentum) - v_prev * momentum # dampening momentum z = np.clip(z, -1, 1) # debugging -- save best gen img of ea. iteration if savegenerated: best = inpaint.get_best_generated(gen_images, loss) bests.append(best) for b in bests: im = toimage(b) im.save("generated/z_" + str(i) + ".jpg") self.progressbar['value'] = i + 1 self.progressbar.update_idletasks() best_image = inpaint.get_best_generated(gen_images, loss) # poisson blending blend_src = np.asarray(toimage(best_image)) mask = preinpaint.bin_inv_mask(self.msk) mask = np.asarray(toimage(mask)) self.completed_img = postinpaint.blend(self.blend_tar, blend_src, mask) # print(self.blend_tar.shape, blend_src.shape, mask.shape) # self.completed_img = inpaint.inpaint(img, best_image, self.msk) disp_img = toimage(self.completed_img) disp_img = disp_img.resize((128, 128), Image.ANTIALIAS) imgtk = ImageTk.PhotoImage(disp_img) txt_lbl = Label(self, text="Completed Image: ") txt_lbl.place(x=250, y=330) dis_img = Label(self, image=imgtk) dis_img.image = imgtk dis_img.place(x=250, y=347) def clickHelp(self): toplevel = Toplevel(root) toplevel.title("Help") with open("files/about.txt", "r") as f: Label(toplevel, text=f.read(), height=20, width=100).pack() def closetl(): toplevel.destroy() Button(toplevel, text="Close", command=closetl).pack() def setParams(self): tl = Toplevel(root) tl.title("Set Parameters") Label(tl, text="Iterations: ").grid(row=0, column=0, sticky=W, padx=5, pady=3) self.iters = Entry(tl, width=10) self.iters.grid(row=0, column=1, padx=5, pady=3) Label(tl, text="Use weighted mask?: ").grid(row=1, column=0, padx=5, pady=3) self.maskedbool = BooleanVar() Radiobutton(tl, text="Yes", variable=self.maskedbool, value=True).grid(row=1, column=1) Radiobutton(tl, text="No", variable=self.maskedbool, value=False).grid(row=1, column=2) # Checkbutton(tl, text="Use weighted mask?", variable=self.maskedbool).grid(row=1, column=3) ch1 = Checkbutton(tl, text="Save mask?", variable=self.saveMask) ch1.grid(row=2, column=0, padx=5, pady=7) ch2 = Checkbutton(tl, text="Save masked image?", variable=self.saveMaskedIm) ch2.grid(row=2, column=1, padx=5, pady=7) def closetl(): tl.destroy() def changeParams(): try: if int(self.iters.get()) > 0: self.nitrs = int(self.iters.get()) else: messagebox.showwarning("Error", "You need at least 1 iteration.") self.weighted_mask = self.maskedbool.get() if self.mask_type.get() != "Select Mask Type": self.display_mask(self.mask_type.get()) if self.show_mskedim: self.display_masked_img() tl.destroy() except ValueError: self.weighted_mask = self.maskedbool.get() if self.mask_type.get() != "Select Mask Type": self.display_mask(self.mask_type.get()) tl.destroy() Button(tl, text="Ok", command=changeParams).grid(row=3, column=2, padx=5, pady=3) Button(tl, text="Cancel", command=closetl).grid(row=3, column=3, padx=5, pady=3)
class AppTracker(Frame): def __init__(self, parent): Frame.__init__(self, parent) # widgets self._status_label = Label(parent, anchor="w", font=("Gisha", 8), text="", background="#d9d9d9", foreground="#3f3f3f") self._status_label.grid(sticky="NEWS", row=1, rowspan=1, column=0, columnspan=3, ipady=1) self._progress_bar = Progressbar(parent, maximum=40, mode='determinate', orient="horizontal") self._loading_bar = Progressbar(parent, maximum=40, mode='indeterminate', orient="horizontal") # self._preset_button = Button(parent, border=0, font=("Gisha", 8), text="Change preset file..") # self._preset_button.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) @property def loading_bar(self): return self._loading_bar @property def progress_bar(self): return self._progress_bar @property def status_label(self): return self._status_label # @property # def preset_button(self): # return self._preset_button def show_loading_bar(self): self._loading_bar.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) self._loading_bar.update_idletasks() def hide_loading_bar(self): self._loading_bar.stop() self._loading_bar.grid_forget() self._loading_bar.update_idletasks() def show_progress_bar(self): self._progress_bar.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) self._progress_bar.update_idletasks() def hide_progress_bar(self): self._progress_bar.grid_forget() self._progress_bar.update_idletasks() def update_status_label(self, text): self._status_label.configure(text=text) self._status_label.update_idletasks() def update_progress_bar(self, value): self._progress_bar['value'] = value self._progress_bar.update_idletasks() def update_loading_bar(self, value): self._loading_bar.step(value) self._loading_bar.update_idletasks()
class FrameDownload(Frame): def __init__(self, master=None, option=()): super().__init__(master=master) self.master = master self.master.title('Download information') self.option = option self.setupUI() def setupUI(self): # build UI base on URLS if self.option[2] == SEARCH: # title window label_title = Label(self, text='Search Photos') label_title.config(anchor='center', foreground='white', background='#8e44ad') label_title.grid(row=0, column=0, columnspan=6, sticky='we') # progress self.progress = Progressbar(self) self.progress.config(orient='horizontal', length=100, mode='determinate') self.progress.grid(row=2, column=0, columnspan=5, sticky='we') self.var_progress = StringVar() self.var_progress.set('0%') self.label_show_progress = Label(self) self.label_show_progress.config(textvariable=self.var_progress, anchor='center') self.label_show_progress.var = self.var_progress self.label_show_progress.grid(row=2, column=5, sticky='w') # query self.label_query = Label(self, text='Query') self.label_query.grid(row=1, column=0, sticky='e') self.var_entry_query = StringVar() self.entry_query = Entry(self) self.entry_query.config(textvariable=self.var_entry_query, state='readonly') self.entry_query.grid(row=1, column=1, sticky='w') # total self.var_total = StringVar() self.var_total.set('Total') self.label_total = Label(self, textvariable=self.var_total) self.label_total.grid(row=1, column=2, sticky='e') self.var_entry_total = IntVar() self.entry_total = Entry(self) self.entry_total.config(textvariable=self.var_entry_total, state='readonly') self.entry_total.grid(row=1, column=3, sticky='w') # total pages self.label_total_page = Label(self, text='Total pages:') self.label_total_page.grid(row=1, column=4, sticky='e') self.var_entry_total_pages = IntVar() self.entry_total_page = Entry(self) self.entry_total_page.config(textvariable=self.var_entry_total_pages, state='readonly') self.entry_total_page.grid(row=1, column=5, sticky='w') # show image is downloaded self.label_image_downloaded = Label(self, anchor='center') self.label_image_downloaded.grid(row=3, column=0, columnspan=6, sticky='wesn') # self.change_ui() elif self.option[2] == LIST: # title window label_title = Label(self, text='List of Photos') label_title.config( anchor='center', foreground='white', background='#2c3e50') label_title.grid(row=0, column=0, columnspan=4, sticky='we') # progress self.progress = Progressbar(self) self.progress.config(orient='horizontal', length=100, mode='determinate') self.progress.grid(row=2, column=0, columnspan=3, sticky='we') self.var_progress = StringVar() self.var_progress.set('0%') self.label_show_progress = Label(self) self.label_show_progress.config( textvariable=self.var_progress, anchor='center') self.label_show_progress.var = self.var_progress self.label_show_progress.grid(row=2, column=3, sticky='w') # query self.label_query = Label(self, text='Query:') self.label_query.grid(row=1, column=0, sticky='e') self.entry_query = Entry(self) self.entry_query.insert(0,'LIST') self.entry_query.config(state='readonly') self.entry_query.grid(row=1, column=1, sticky='w') # amount self.label_total = Label(self, text='Amount:') self.label_total.grid(row=1, column=2, sticky='e') self.entry_total = Entry(self) self.entry_total.insert(0,self.option[3]['per_page']) self.entry_total.config(state='readonly') self.entry_total.grid(row=1, column=3, sticky='w') # show image is downloaded self.label_image_downloaded = Label(self, anchor='center') self.label_image_downloaded.grid( row=3, column=0, columnspan=4, sticky='wesn') # self.change_ui() elif self.option[2] == RANDOM: # title window label_title = Label(self, text='Random Photos') label_title.config( anchor='center', foreground='white', background='#16a085') label_title.grid(row=0, column=0, columnspan=4, sticky='we') # progress self.progress = Progressbar(self) self.progress.config(orient='horizontal', length=100, mode='determinate') self.progress.grid(row=2, column=0, columnspan=3, sticky='we') self.var_progress = StringVar() self.var_progress.set('0%') self.label_show_progress = Label(self) self.label_show_progress.config( textvariable=self.var_progress, anchor='center') self.label_show_progress.var = self.var_progress self.label_show_progress.grid(row=2, column=3, sticky='w') # query self.label_query = Label(self, text='Query') self.label_query.grid(row=1, column=0, sticky='e') self.entry_query = Entry(self) self.entry_query.insert(0,'RANDOM') self.entry_query.config(state='readonly') self.entry_query.grid(row=1, column=1, sticky='w') # amount self.label_total = Label(self, text='Amount') self.label_total.grid(row=1, column=2, sticky='e') self.var_entry_total = IntVar() if self.option[3]['count'] > 30: self.var_entry_total.set(30) else: self.var_entry_total.set(self.option[3]['count']) self.entry_total = Entry(self) self.entry_total.config(textvariable=self.var_entry_total, state='readonly') self.entry_total.grid(row=1, column=3, sticky='w') # show image is downloaded self.label_image_downloaded = Label(self, anchor='center') self.label_image_downloaded.grid( row=3, column=0, columnspan=4, sticky='wesn') def change_ui(self): if self.option[2] == SEARCH: r = requests.get(self.option[2], params=self.option[3]) if r.status_code == 200: # get urls based on quality j = json.loads(r.text) total = j['total'] total_pages = j['total_pages'] results = j['results'] self.var_entry_query.set(self.option[3]['query']) self.var_entry_total.set(total) self.var_entry_total_pages.set(total_pages) self.entry_query.update_idletasks() self.entry_total.update_idletasks() self.entry_total_page.update_idletasks() # random photos elif self.option[2] == RANDOM: r = requests.get(self.option[2], params=self.option[3]) if r.status_code == 200: # get result j = json.loads(r.text) results = j elif self.option[2] == LIST: r = requests.get(self.option[2], params=self.option[3]) if r.status_code == 200: # get result j = json.loads(r.text) results = j self.download(results) def download(self, results): for i in results: name = i['id'] url = i['urls'][self.option[1]] time.sleep(1) # delay time to send request try: request.urlretrieve(url, self.option[0]+'/'+name+'.jpg') except Exception as x: # re download if have a problem print('have problem', x) time.sleep(1) self.progress['value'] += 100/len(results) self.var_progress.set('{}%'.format(self.progress['value'])) # show image downloaded image = Image.open(self.option[0]+'/'+name+'.jpg') width = int(self.winfo_width()) height = int(width*image.height/image.width) self.photo = ImageTk.PhotoImage( image.resize((width, height), Image.ANTIALIAS)) self.label_image_downloaded.config(image=self.photo) self.label_image_downloaded.image = self.photo self.progress.update_idletasks() self.message_done = messagebox.showinfo('Info', 'Done') self.master.destroy()
class BulkDownloader(object): def __init__(self, window, running, data, count, progress_value): # variables self.running = running self.data = data self.count = count self.progress_value = progress_value # master/parent window contains all gui elements self.window = window window.title("TNRIS DataHub Bulk Download Utility") # frame variables - parent is window self.top_frame = tk.Frame(window, borderwidth=10) self.middle_frame_1 = tk.Frame(window, borderwidth=10) self.middle_frame_2 = tk.Frame(window, borderwidth=10) self.middle_left_frame_2 = tk.Frame(self.middle_frame_2, borderwidth=10) self.middle_left_frame_2.pack(side='left', expand=1) self.middle_right_frame_2 = tk.Frame(self.middle_frame_2, borderwidth=10) self.middle_right_frame_2.pack(side='right', expand=1) self.middle_frame_3 = tk.Frame(window, borderwidth=10, padx=10) self.middle_frame_4 = tk.Frame(window, borderwidth=10) self.bottom_frame = tk.Frame(window, borderwidth=10, pady=10) self.frame_list = [ self.top_frame, self.middle_frame_1, self.middle_frame_2, self.middle_frame_3, self.middle_frame_4, self.bottom_frame ] # for loop to pack all frames for f in self.frame_list: f.pack(fill='both') # label variables self.label_1 = tk.Label(self.top_frame, text="Enter a TNRIS DataHub Collection ID: ") self.label_2 = tk.Label(self.middle_frame_1, text="If the collection entered has multiple resource types, filter them here.") self.label_3 = tk.Label(self.middle_frame_1, text="No filter selection will result in all collection resources downloaded.") self.label_list = [self.label_1, self.label_2, self.label_3] # for loop to configure all labels with font for l in self.label_list: l.configure(font=('Courier', 10, 'bold')) l.pack(fill='both') # collection id entry self.collection_id = tk.Entry(self.top_frame, width=45, font=('Courier', 10)) self.collection_id.pack() self.collection_id.focus() self.label_4 = tk.Label(self.top_frame, text="Browse to a directory where you can save your downloaded data.") self.label_5 = tk.Label(self.middle_left_frame_2, text="Lidar") self.label_6 = tk.Label(self.middle_right_frame_2, text="Imagery") self.lbl_list = [self.label_4, self.label_5, self.label_6] for lbl in self.lbl_list: lbl.config(font=('Courier', 10, 'bold'), pady=10) lbl.pack(fill='both') # resource types check box variables - onvalue string is used in the api query (resource_type_abbreviation) self.type_value = tk.StringVar() self.type_value.set("") self.type_1 = tk.Checkbutton(self.middle_left_frame_2, text="Lidar Point Cloud", var=self.type_value, onvalue="LPC", offvalue="") self.type_2 = tk.Checkbutton(self.middle_left_frame_2, text="Hypsography", var=self.type_value, onvalue="HYPSO", offvalue="") self.type_3 = tk.Checkbutton(self.middle_left_frame_2, text="Digital Elevation Model", var=self.type_value, onvalue="DEM", offvalue="") self.type_placeholder = tk.Label(self.middle_left_frame_2, text="") # this empty label is used for alignment self.type_4 = tk.Checkbutton(self.middle_right_frame_2, text="Color Infrared (3 Band)", var=self.type_value, onvalue="CIR", offvalue="") self.type_5 = tk.Checkbutton(self.middle_right_frame_2, text="Natural Color (3 Band)", var=self.type_value, onvalue="NC", offvalue="") self.type_6 = tk.Checkbutton(self.middle_right_frame_2, text="Natural Color/Color Infrared (4 Band)", var=self.type_value, onvalue="NC-CIR", offvalue="") self.type_7 = tk.Checkbutton(self.middle_right_frame_2, text="Black & White (1 Band)", var=self.type_value, onvalue="BW", offvalue="") self.type_list = [self.type_1, self.type_2, self.type_3, self.type_placeholder, self.type_4, self.type_5, self.type_6, self.type_7] # for loop to pack & configure checkbuttons for t in self.type_list: t.config(font=('Courier', 10)) t.pack(fill="both") # Progress bar widget self.progress = Progressbar(self.middle_frame_3, orient='horizontal') self.progress.pack(fill='both') # Progress bar config self.progress.config(mode='determinate', value=0, maximum=100) # print messages from the downloader method self.display_message_1 = tk.StringVar() self.display_message_2 = tk.StringVar() self.error_message = tk.StringVar() self.display_message_1.set("Messages here provide download progress feedback.") self.message_area_1 = tk.Label(self.middle_frame_4, textvariable=self.display_message_1, font=('Courier', 10)) self.message_area_2 = tk.Label(self.middle_frame_4, textvariable=self.display_message_2, font=('Courier', 10), fg='green') self.message_area_3 = tk.Label(self.middle_frame_4, textvariable=self.error_message, font=('Courier', 10), fg='red') self.message_area_list = [self.message_area_1, self.message_area_2, self.message_area_3] # for loop to pack message areas for a in self.message_area_list: a.pack(fill='both') self.folder_path = tk.StringVar() self.label_4 = tk.Label(self.top_frame, textvariable=self.folder_path) self.label_4.configure(font=('Courier', 10), pady=10) self.label_4.pack(fill='both') # pack buttons that run methods self.browse = tk.Button(self.top_frame, text="Browse", command=self.browse_button) self.browse.pack() self.getdata = tk.Button(self.bottom_frame, text="Get Data", command=self.start) self.getdata.pack(side='right', expand=1) self.stop_it = tk.Button(self.bottom_frame, text="Stop", command=self.stop) self.stop_it.pack(side='left', expand=1) # Allow user to select a directory and store it in global var called folder_path def browse_button(self): self.folder_path self.filename = filedialog.askdirectory() self.folder_path.set(self.filename) print('folder_path variable:', self.folder_path.get()) return self.folder_path # fires the main method on its own separate thread def start(self): self.main_thread = threading.Thread(name='starter', target=self.get_data) self.main_thread.start() # method to set up separate thread and target for kill method # fired when the stop button is clicked def stop(self): self.kill_thread = threading.Thread(name='killer', target=self.kill(self.running)) self.kill_thread.start() # this method changes the running variable from True to None and stops the main # downloader method from running / breaks the for loop when running = None def kill(self, running): response = messagebox.askokcancel(title="Stop Downloading", message="Are you sure you want to stop downloading?") # if ok button clicked to quit, set running var to None which will stop the for loop if response: print("stopping bulk downloader...") self.running = None # method to check if a valid uuid is provided def valid_uuid(self, val): try: UUID(str(val)) return True except ValueError: return False # progress bar update method def p_bar(self, value): self.progress['value'] = value self.progress.update_idletasks() def get_data(self): self.display_message_1.set("Messages here provide download progress feedback.") # reset feedback message self.display_message_2.set("") # reset feedback message self.error_message.set("") # reset any error messages c = self.collection_id.get() t = self.type_value.get() self.count = 0 base_url = "https://api.tnris.org/api/v1/resources/" id_query = "?collection_id=" type_query = "&resource_type_abbreviation=" # area_query = "&area_type=" # first check to make sure the collection id string is a valid using valid_uuid method # then check if the folder_path directory to save the data exists # then assign data variable based on checkbox selections (build the url string requests needs to get data from rest endpoint) if self.valid_uuid(c): if os.path.exists(self.folder_path.get()): if c and not t: # if no selections made, build url string to get all resources for that collection id print('no selections made') self.data = requests.get(base_url + id_query + c).json() elif c and t: # if type selection made but not area, build the url string print('type selection made. type = {}'.format(t)) ''' possible future enhancement here to add ability to handle multiple resource type filters ''' self.data = requests.get(base_url + id_query + c + type_query + t).json() else: # retrun message to the user that there was a problem with the directory chosen to save downloaded data print("Error. Check the directory provided to save data.") self.error_message.set("Error. Check the directory provided to save data.") self.message_area_3.update_idletasks() return else: print("Error. Check the collection id provided.") self.error_message.set("Error. Check the collection id provided.") self.message_area_3.update_idletasks() return # run the downloader method if self.data: self.downloader(self.running, self.data, self.count) def downloader(self, running, data, count): # main method that iterates over api results and downloads collection resources api_num_count = self.data['count'] api_str_count = str(self.data['count']) if self.data['count'] > 0: for obj in self.data['results']: if self.running: try: # count each file written self.count += 1 print("{} | downloading resource id: {}".format(self.count, obj['resource'].rsplit('/', 1)[-1])) # update progress_value variable by dividing new count number by total api object count self.progress_value = round((self.count/api_num_count)*100) # feed new progress value into p_bar function to update gui self.p_bar(self.progress_value) # show display message/text as progress percentage string self.display_message_1.set("{}/{} resources downloaded".format(self.count, api_str_count)) self.display_message_2.set("download progress: " + str(self.progress_value) + "%") # make sure message area/labels are updated self.message_area_1.update_idletasks() self.message_area_2.update_idletasks() # assign next object['resource'] url to file variable if os.path.exists('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])): continue file = requests.get(obj["resource"], stream=True) # write file variable to actual local zipfile saving to user provided directory and doing it in chunks with open('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1]), 'wb') as zipfile: for chunk in file.iter_content(chunk_size=1024): if chunk: zipfile.write(chunk) # sepcific requests library exceptions to catch any errors getting data from the api except requests.exceptions.HTTPError as http_error: print ("http error:", http_error) self.error_message.set("http error: ", http_error) self.message_area_3.update_idletasks() os.remove('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])) except requests.exceptions.ConnectionError as connection_error: print ("error connecting:", connection_error) self.error_message.set("error connecting: ", connection_error) self.message_area_3.update_idletasks() os.remove('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])) except requests.exceptions.Timeout as timeout_error: print ("timeout error:", timeout_error) self.error_message.set("timeout error: ", timeout_error) self.message_area_3.update_idletasks() os.remove('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])) # general catch all requests library exception to catch an error if it is outside the above exceptions except requests.exceptions.RequestException as general_error: print ("OOps, there was some error: ", general_error) self.error_message.set("OOps, there was some error: ", general_error) self.message_area_3.update_idletasks() os.remove('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])) else: # if user stops program, display message print("Bulk Downloader stopped.") self.error_message.set("Bulk Downloader stopped.") self.message_area_3.update_idletasks() if os.path.exists('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])): os.remove('{}/{}'.format(self.folder_path.get(), obj['resource'].rsplit('/', 1)[-1])) return else: # return a message to the user that there is an error with either the collection id string or the filter applied print("Error. No resource results. Check your collection id or filters applied.") self.error_message.set("Error. No resource results. Check your collection id or filters applied.") self.message_area_3.update_idletasks() # if first page of resources downloaded successfully, run paginator method to see if there are additional pages self.paginator(self.running, self.count) def paginator(self, running, count): # check if next value present for pagination; if so, use it as data variable and re-run downloader method while self.data['next']: self.data = requests.get(self.data['next']).json() count = self.downloader(running, self.data, count)
class MainView(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs); self.toForeGround ################### init, main config ###################### container = Frame(self, bg=bgColor); container.pack(side="top", fill="both", expand=True); self.ft1 = font.Font(family='Arial', size=11); self.ft2 = font.Font(family='MS Gothic', size=10); self.ft3 = font.Font(family='Arial', size=9); self.ft4 = font.Font(family='Arial', size=10); self.ft5 = font.Font(family='Arial', size=14); self.ft6 = font.Font(family="Courier", size = 9); self.p1 = Page1(container, bg=container["background"]); self.p2 = Page2(container, bg=container["background"]); self.p3 = Page3(container, bg=container["background"]); self.p4 = Page4(container, bg=container["background"]); self.p5 = Page5(container, bg=container["background"]); self.p6 = Page6(container, bg=container["background"]); self.p7 = Page7(container, bg=container["background"]); self.p8 = Page8(container, bg=container["background"]); self.p9 = Page9(container, bg=container["background"]); topBar = Frame(container, bg=topBarColor, width=container.winfo_width() * framewidth, height=topBarHeight); topBar.place(x=0, y=0); self.p1.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p2.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p3.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p4.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p5.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p6.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p7.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p8.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p9.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); close= Button(topBar, text=u"\u2715", command= lambda: self.close(), bg=topBar["background"], bd=0, font = self.ft2, fg=fgColor, activebackground="#940000"); close.place(x = topBar["width"] - topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); minim = Button(topBar, text="_", command= lambda: self.toicon(), bg=topBar["background"], bd=0, font=self.ft2, fg=fgColor, activebackground="#364969"); minim.place(x = topBar["width"] - 2 * topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); label = Label(topBar, text=title, font=self.ft3, bg=topBar["background"], fg=fgColor); label.place(x = 5, y = 0, height= topBar["height"]); #event handlers so the window can be moved topBar.bind("<ButtonPress-1>", self.StartMove); topBar.bind("<ButtonRelease-1>", self.StopMove); topBar.bind("<B1-Motion>", self.OnMotion); label.bind("<ButtonPress-1>", self.StartMove); label.bind("<ButtonRelease-1>", self.StopMove); label.bind("<B1-Motion>", self.OnMotion); close.bind("<Enter>", self.closeEnterBG); close.bind("<Leave>", self.topBarButtonNormalBG); minim.bind("<Enter>", self.minimEnterBG); minim.bind("<Leave>", self.topBarButtonNormalBG); self.master.bind("<Unmap>", self.toiconify); self.master.bind("<Map>", self.todeiconify); ##################### page 1, intro ############################ T1 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T1.place(x=10, y=10); HelpButton = Label(self.p1, text = "help", background=bgColor, fg = hyperlinkColor, font = self.ft5, cursor="hand2"); HelpButton.place(x=8, y=53); underlineFont = font.Font(HelpButton, HelpButton.cget("font")); underlineFont.configure(underline = True); HelpButton.configure(font=underlineFont); HelpButton.bind("<Button-1>", lambda x: self.clickHelp()) T2 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T2.place(x=53, y=55); T1.insert(END, "Welcome to the ELS Scorion tool. Click next to select what tool to use, or press\n"); T2.insert(END, "to learn more about the tool."); T1.configure(state=DISABLED); T2.configure(state=DISABLED); nextButtonP1 = Button(self.p1, text = "Next", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); nextButtonP1.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); nextButtonP1.bind("<Enter>", self.buttonEnterBG); nextButtonP1.bind("<Leave>", self.buttonNormalBG); ################## page 2, task picker ######################### instrLabel = Label(self.p2, text = "Choose what tool to use", bg=self.p2["background"], fg=fgColor, font=self.ft5); instrLabel.place(x= 30, y = 10); buildGroupsButton = Button(self.p2, text = "Build Scorion groups", command=self.p3.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); buildGroupsButton.place(x = 75, y = 48, width = 250, height = 2*nextprevButtonHeight); buildGroupsButton.bind("<Enter>", self.buttonEnterBG); buildGroupsButton.bind("<Leave>", self.buttonNormalBG); splitGroupsButton = Button(self.p2, text = "Split Scorion file", command=self.p4.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); splitGroupsButton.place(x = 75, y = 120, width = 250, height = 2*nextprevButtonHeight); splitGroupsButton.bind("<Enter>", self.buttonEnterBG); splitGroupsButton.bind("<Leave>", self.buttonNormalBG); onlyFileButton = Button(self.p2, text = "Only create Scorion file", command=self.p5.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); onlyFileButton.place(x = 75, y = 192, width = 250, height = 2*nextprevButtonHeight); onlyFileButton.bind("<Enter>", self.buttonEnterBG); onlyFileButton.bind("<Leave>", self.buttonNormalBG); possibleErrorButton = Button(self.p2, text = "Find errors in file", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); possibleErrorButton.place(x = 75, y = 264, width = 250, height = 2*nextprevButtonHeight); possibleErrorButton.bind("<Enter>", self.buttonEnterBG); possibleErrorButton.bind("<Leave>", self.buttonNormalBG); previousButtonP2 = Button(self.p2, text = "Back", command=self.p1.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP2.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP2.bind("<Enter>", self.buttonEnterBG); previousButtonP2.bind("<Leave>", self.buttonNormalBG); ################## page 3, group builder ######################## previousButtonP3 = Button(self.p3, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP3.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP3.bind("<Enter>", self.buttonEnterBG); previousButtonP3.bind("<Leave>", self.buttonNormalBG); courseIdWrap = Frame(self.p3, bg= self.p3["background"]); courseIdWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar = StringVar(); self.courseVar.trace("w", lambda name, index, mode, courseVar=self.courseVar: self.firecallback()); courseIdLabel = Label(courseIdWrap, text = "Course Id:", bg=self.p3["background"], fg=fgColor, font=self.ft4); courseIdLabel.place(x= 0, y = 0, height = topBarHeight); courseId = Entry(courseIdWrap, width= 45, bg=bg2Color, textvariable=self.courseVar,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId.place(x = 65, y = 0, height=topBarHeight); fileWrap = Frame(self.p3, bg =self.p3["background"]); fileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel = Label(fileWrap, text = "File:", bg=self.p3["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 30, y = 0, height = topBarHeight); self.fileVar = StringVar(); self.fileVar.trace("w", lambda name, index, mode, fileVar=self.fileVar: self.firecallback()); self.fileName = Entry(fileWrap, width= 36, textvariable=self.fileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName.place(x = 65, y = 0, height= topBarHeight); #TODO: drag files into the text field self.browse = Button(fileWrap, text="Browse", command=self.load_file, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse.place(x=326, y=0, height = topBarHeight, width=60); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); seperatorWrap = Frame(self.p3, bg = self.p3["background"]); seperatorWrap.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel = Label(seperatorWrap, text="What seperator is used in the file?", bg=self.p3["background"], fg=fgColor, font=self.ft4); optionLabel.place(x = 0, y = 0, height = topBarHeight); optionList = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar = StringVar(); self.sepVar.set(optionList[0][1]); commaButton = Radiobutton(seperatorWrap, text=optionList[0][0], variable = self.sepVar, value=optionList[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton = Radiobutton(seperatorWrap, text=optionList[1][0], variable = self.sepVar, value=optionList[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton.place(x=260, y = topBarHeight + 2, width = 120); optionLabel = Label(self.p3, text="Do you already have a Scorion File?"); scorionCheckWrap = Frame(self.p3, bg = self.p3["background"]); scorionCheckWrap.place(x=10, y = 194, height=topBarHeight, width = framewidth - 20); self.checkVar = IntVar(); scorionCheck = Checkbutton(scorionCheckWrap, text="Create a Scorion file?", var = self.checkVar, font=self.ft4, fg=fgColor, bg=bg2Color, bd=0, highlightthickness = 0, selectcolor=bg2Color, activeforeground=fgColor, activebackground= bg2Color); scorionCheck.select(); scorionCheck.place(x=210, y=0, height=topBarHeight, width = 170); self.goButton = Button(self.p3, text = "Run", command=self.combineFuncs, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButton.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 4, split groups page ######################## previousButtonP4 = Button(self.p4, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP4.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP4.bind("<Enter>", self.buttonEnterBG); previousButtonP4.bind("<Leave>", self.buttonNormalBG); scorFileWrap = Frame(self.p4, bg =self.p4["background"]); scorFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight); fileLabel = Label(scorFileWrap, text = "Scorion File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 0, y = 0, height = topBarHeight); self.scorFileVar = StringVar(); self.scorFileVar.trace("w", lambda name, index, mode, scorFileVar=self.scorFileVar: self.firecallback1()); self.scorFileName = Entry(scorFileWrap, width= 34, textvariable=self.scorFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.scorFileName.place(x = 79, y = 0, height= topBarHeight); self.browse1 = Button(scorFileWrap, text="Browse", command=self.load_file1, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse1.place(x=326, y=0, height = topBarHeight, width=60); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); errFileWrap = Frame(self.p4, bg =self.p4["background"]); errFileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); errLabel = Label(errFileWrap, text = "Error File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); errLabel.place(x= 0, y = 0, height = topBarHeight); self.errFileVar = StringVar(); self.errFileVar.trace("w", lambda name, index, mode, errFileVar=self.errFileVar: self.firecallback1()); self.errFileName = Entry(errFileWrap, width= 36, textvariable=self.errFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.errFileName.place(x = 65, y = 0, height= topBarHeight); self.browse2 = Button(errFileWrap, text="Browse", command=self.load_file2, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse2.place(x=326, y=0, height = topBarHeight, width=60); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); self.goButtonP4 = Button(self.p4, text = "Run", command=self.combineFuncs2, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP4.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 5, only create groups page ################## previousButtonP5 = Button(self.p5, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP5.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP5.bind("<Enter>", self.buttonEnterBG); previousButtonP5.bind("<Leave>", self.buttonNormalBG); courseIdWrap2 = Frame(self.p5, bg= self.p5["background"]); courseIdWrap2.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar2 = StringVar(); self.courseVar2.trace("w", lambda name, index, mode, courseVar2=self.courseVar2: self.firecallback2()); courseIdLabel2 = Label(courseIdWrap2, text = "Course Id:", bg=self.p5["background"], fg=fgColor, font=self.ft4); courseIdLabel2.place(x= 0, y = 0, height = topBarHeight); courseId2 = Entry(courseIdWrap2, width= 45, bg=bg2Color, textvariable=self.courseVar2,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId2.place(x = 65, y = 0, height=topBarHeight); fileWrap2 = Frame(self.p5, bg =self.p5["background"]); fileWrap2.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel2 = Label(fileWrap2, text = "File:", bg=self.p5["background"], fg=fgColor, font=self.ft4); fileLabel2.place(x= 30, y = 0, height = topBarHeight); self.fileVar2 = StringVar(); self.fileVar2.trace("w", lambda name, index, mode, fileVar2=self.fileVar2: self.firecallback2()); self.fileName2 = Entry(fileWrap2, width= 36, textvariable=self.fileVar2,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName2.place(x = 65, y = 0, height= topBarHeight); self.browse3 = Button(fileWrap2, text="Browse", command=self.load_file3, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse3.place(x=326, y=0, height = topBarHeight, width=60); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); seperatorWrap2 = Frame(self.p5, bg = self.p5["background"]); seperatorWrap2.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel2 = Label(seperatorWrap2, text="What seperator is used in the file?", bg=self.p5["background"], fg=fgColor, font=self.ft4); optionLabel2.place(x = 0, y = 0, height = topBarHeight); optionList2 = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar2 = StringVar(); self.sepVar2.set(optionList2[0][1]); commaButton2 = Radiobutton(seperatorWrap2, text=optionList2[0][0], variable = self.sepVar2, value=optionList2[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton2 = Radiobutton(seperatorWrap2, text=optionList2[1][0], variable = self.sepVar2, value=optionList2[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton2.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton2.place(x=260, y = topBarHeight + 2, width = 120); self.goButtonP5 = Button(self.p5, text = "Run", command=self.combineFuncs3, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP5.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 6, progress page ########################### self.cancelButton = Button(self.p6, text = "cancel", command=lambda:sys.exit(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.cancelButton.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.cancelButton.bind("<Enter>", self.buttonEnterBG); self.cancelButton.bind("<Leave>", self.buttonNormalBG); self.progressLabel = Label(self.p6, text = "Working, this might take a couple of minutes...", bg=self.p6["background"], fg=fgColor, font=self.ft1) self.progressLabel.place(x=10, y=36); #TODO: make the progressbar actually progress to the things that are done style = Style(); style.theme_use('alt') style.configure("els.Horizontal.TProgressbar", background=fgColor); self.progress = Progressbar(self.p6, orient=HORIZONTAL, length = framewidth - 20, mode="indeterminate", style="els.Horizontal.TProgressbar", maximum=40); self.progress.place(x=10, y=10); self.progress.start(17); self.closeP6 = Button(self.p6, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); ################### page 7, error page ########################### #TODO: implement full stacktrace instead of only 2 #TODO: or: make a log file of the stacktrace that can be "downloaded" when clicked #TODO: error page is not working correctly anymore; errors are being cut off self.errorLabel = Label(self.p7, text = "Something went wrong, try again or contact Cas", bg=self.p7["background"], fg=errorColor, font=self.ft1); self.errorLabel.place(x=36, y=10); self.errorInfoLabel = Label(self.p7, text = "Error Info:", bg=self.p7["background"], fg=fgColor, font=self.ft1); self.errorInfoLabel.place(x=36, y=50); self.stackTraceStringVar1 = StringVar(); self.stackTraceStringVar2 = StringVar(); self.stackTraceLabel1 = Label(self.p7, textvariable = self.stackTraceStringVar1, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceLabel2 = Label(self.p7, textvariable = self.stackTraceStringVar2, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.stackTraceLabel1.place(x=36, y=70); self.stackTraceLabel2.place(x=36, y=110); self.backToMenu = Button(self.p7, text = "Back to menu", command=self.backtomenu, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.backToMenu.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.backToMenu.bind("<Enter>", self.buttonEnterBG); self.backToMenu.bind("<Leave>", self.buttonNormalBG); self.closeP7 = Button(self.p7, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.closeP7.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP7.bind("<Enter>", self.buttonEnterBG); self.closeP7.bind("<Leave>", self.buttonNormalBG); ################### page 8, find error page ########################### previousButtonP8 = Button(self.p8, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP8.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP8.bind("<Enter>", self.buttonEnterBG); previousButtonP8.bind("<Leave>", self.buttonNormalBG); checkErrFileWrap = Frame(self.p8, bg =self.p8["background"]); checkErrFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = 3*topBarHeight); checkErrLabel = Label(checkErrFileWrap, text = "File to check for Errors:", bg=self.p4["background"], fg=fgColor, font=self.ft4); checkErrLabel.place(x= 0, y = 0, height = topBarHeight); self.checkErrFileVar = StringVar(); self.checkErrFileVar.trace("w", lambda name, index, mode, checkErrFileVar=self.checkErrFileVar: self.firecallback3()); self.checkErrFileName = Entry(checkErrFileWrap, width= 45, textvariable=self.checkErrFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.checkErrFileName.place(x = 2, y = 25, height= topBarHeight); self.browse4 = Button(checkErrFileWrap, text="Browse", command=self.load_file4, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse4.place(x=326, y=25, height = topBarHeight, width=60); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); self.goButtonP8 = Button(self.p8, text = "Run", command=self.p9.lift, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP8.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 9, find error results ########################### previousButtonP9 = Button(self.p9, text = "Back", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP9.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP9.bind("<Enter>", self.buttonEnterBG); previousButtonP9.bind("<Leave>", self.buttonNormalBG); #testing self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, r"M:\ud\os\ssc\imos\bbsup\@ new folder_Surfdrive\7. Scorion\Vakmappen 171804\46597-171804\group_import_no_TAs.txt"); self.errors = errorChecker(self.checkErrFileVar.get()); self.croppedErrors = self.errors[0:7] if (len(self.errors) > 0): Label(self.p9, text = "Found %d possible errors, on the following lines:" %len(self.errors), fg = fgColor, bg = bgColor, font = self.ft1).place(x=16, y=12); openFile = Button(self.p9, text = "Open file", command=lambda: self.clickOpenFile(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); openFile.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); openFile.bind("<Enter>", self.buttonEnterBG); openFile.bind("<Leave>", self.buttonNormalBG); self.drawErrors(); else: Label(self.p9, text = "Found no errors", fg = fgColor, bg = bgColor, font = self.ft5).place(x=10, y=10); ################### finally, show page 1 to start ################ self.p1.show(); ################### window event handlers ########################## def StartMove(self, event): self.master.x = event.x; self.master.y = event.y; def StopMove(self, event): self.master.x = None; self.master.y = None; def OnMotion(self, event): deltax = event.x - self.master.x; deltay = event.y - self.master.y; x = self.master.winfo_x() + deltax; y = self.master.winfo_y() + deltay; self.master.geometry("+%s+%s" % (x, y)); def toForeGround(self): self.master.lift(); def toicon(self): self.master.update_idletasks(); self.master.overrideredirect(False); self.master.iconify(); def toiconify(self, event): self.master.overrideredirect(False); def todeiconify(self, event): self.master.overrideredirect(True); def closeEnterBG(self, event): event.widget.config(bg="#C40000"); def minimEnterBG(self, event): event.widget.config(bg="#455D85") def topBarButtonNormalBG(self, event): event.widget.config(bg=topBarColor); def buttonEnterBG(self, event): event.widget.config(bg=buttonHoverColor); def buttonNormalBG(self, event): event.widget.config(bg=buttonColor); def buttonEnterDisabledBG(self, event): event.widget.config(bg=disabledButtonColor); def buttonNormalDisabledBG(self, event): event.widget.config(bg=disabledButtonColor); def close(self): self.progress.stop(); self.progress.destroy(); self.master.quit(); ################### other functions ############################## def clickHelp(self): location = "manual.docx"; os.system("start " + location); def clickOpenFile(self): import subprocess; location = self.checkErrFileName.get(); program = resource_path("Notepad++\\notepad++.exe") subprocess.call([program, location]); def showNextErrors(self): startNumber = self.errors.index(self.croppedErrors[0]); self.croppedErrors = self.errors[startNumber + 7:startNumber + 14]; self.drawErrors(); def showPrevErrors(self): startNumber = self.errors.index(self.croppedErrors[0]) self.croppedErrors = self.errors[startNumber - 7:startNumber]; self.drawErrors(); def drawErrors(self): if (len(self.errors) > 7): startNumber = self.errors.index(self.croppedErrors[0]); self.nextErrors = Button(self.p9, text = ">", command=lambda: self.showNextErrors(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); self.prevErrors = Button(self.p9, text = "<", command=lambda: self.showPrevErrors(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); if not (startNumber >= (len(self.errors) - 7)): self.nextErrors.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX + nextprevButtonWidth/2 + 2, y = frameheight - nextprevButtonHeight - 2 * nextprevButtonPaddingY, width = nextprevButtonWidth/2 - 2, height = nextprevButtonHeight); else: print("should hide"); self.hideNextButton(); if (startNumber > 0): self.prevErrors.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - 2 * nextprevButtonPaddingY, width = nextprevButtonWidth/2 - 2, height = nextprevButtonHeight); else: self.prevErrors.lower(); cropRange = 22; ErrorWrap = Frame(self.p9, bg = codeBGColor); ErrorWrap.place(x = 56, y = 40, width = framewidth - 72, height = frameheight - topBarHeight - 124) LineWrap = Frame(self.p9, bg = codeBG2Color); LineWrap.place(x=16, y = 40, width = 40, height = frameheight - topBarHeight - 124); for i in range(len(self.croppedErrors)): formattedLine = str((int(self.croppedErrors[i].getLineOccurence()) + 1)) for k in range(3 - len(formattedLine)): formattedLine = "0" + formattedLine; Label(LineWrap, text = formattedLine, bg = codeBG2Color, font = self.ft6, fg = fgColor).place(x = 6, y = 4+40*i) for i in range(len(self.croppedErrors)): sourceLine = self.croppedErrors[i].getSourceLine(); if (len(sourceLine) - self.croppedErrors[i].getColOccurence()) > cropRange: cropped = sourceLine[max(self.croppedErrors[i].getColOccurence() - cropRange, 0):max(self.croppedErrors[i].getColOccurence() + cropRange, 2 * cropRange)] Label(ErrorWrap, text="^", fg = errorColor, bg = codeBGColor).place(x = min(round(7.05 * cropRange), round(7.1*self.croppedErrors[i].getColOccurence())), y = 20 + 40*i) Label(ErrorWrap, text=cropped, fg = fgColor, bg = codeBGColor, font = self.ft6).place(x = 2, y = 5+40*i) else: EOLOccurence = len(sourceLine) - self.croppedErrors[i].getColOccurence() - 1; cropped = sourceLine[self.croppedErrors[i].getColOccurence() - (2 * cropRange - EOLOccurence):] Label(ErrorWrap, text=cropped, fg = fgColor, bg = codeBGColor, font = self.ft6).place(x = 2, y = 5+40*i) Label(ErrorWrap, text="^", fg = errorColor, bg = codeBGColor).place(x = round(7.05*((2*cropRange) - EOLOccurence)), y = 20 + 40*i) def hideNextButton(self): self.nextErrors.place_forget(); def firecallback(self): if len(self.courseVar.get()) == 0 or len(self.fileVar.get()) == 0: self.goButton.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButton.bind("<Enter>", self.buttonEnterDisabledBG); self.goButton.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButton.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButton.bind("<Enter>", self.buttonEnterBG); self.goButton.bind("<Leave>", self.buttonNormalBG); def firecallback1(self): if len(self.scorFileVar.get()) == 0 or len(self.errFileVar.get()) == 0: self.goButtonP4.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP4.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP4.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP4.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP4.bind("<Enter>", self.buttonEnterBG); self.goButtonP4.bind("<Leave>", self.buttonNormalBG); def firecallback2(self): if len(self.courseVar2.get()) == 0 or len(self.fileVar2.get()) == 0: self.goButtonP5.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP5.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP5.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP5.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP5.bind("<Enter>", self.buttonEnterBG); self.goButtonP5.bind("<Leave>", self.buttonNormalBG); def firecallback3(self): if len(self.checkErrFileVar.get()) == 0: self.goButtonP8.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP8.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP8.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP8.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP8.bind("<Enter>", self.buttonEnterBG); self.goButtonP8.bind("<Leave>", self.buttonNormalBG); def combineFuncs(self): self.p6.lift(); try: self.createGroups(); except Exception as e: self.fireErrorPage(e); return def combineFuncs2(self): self.p6.lift(); try: self.split(); except Exception as e: self.fireErrorPage(e); return def combineFuncs3(self): self.p6.lift(); try: self.createFile(); except Exception as e: self.fireErrorPage(e); return def fireErrorPage(self, e): import traceback; global tb; tb = traceback.format_exc(); traceback.print_exc(); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.p7.lift(); def getStackTrace(self): if len(tb.split("\n")) == 1: return [tb, ""]; elif len(tb.split("\n")) < 4: return [tb.split("\n")[-2].lstrip(), ""]; return [tb.split("\n")[-2].lstrip(), tb.split("\n")[-4].lstrip()]; def load_file(self): self.browse.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse.bind("<Enter>", self.buttonEnterDisabledBG); self.browse.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.fileName.delete(0, END); self.fileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); return def load_file1(self): self.browse1.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse1.bind("<Enter>", self.buttonEnterDisabledBG); self.browse1.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.scorFileName.delete(0, END); self.scorFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse1.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); return def load_file2(self): self.browse2.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse2.bind("<Enter>", self.buttonEnterDisabledBG); self.browse2.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.errFileName.delete(0, END); self.errFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse2.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); return def load_file3(self): self.browse3.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse3.bind("<Enter>", self.buttonEnterDisabledBG); self.browse3.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.fileName2.delete(0, END); self.fileName2.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse3.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); return def load_file4(self): self.browse4.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse4.bind("<Enter>", self.buttonEnterDisabledBG); self.browse4.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse4.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); return def createGroups(self): course_id = self.courseVar.get(); fileName = self.fileVar.get(); seperator = self.sepVar.get(); write = self.checkVar.get() == 1; groups = getGroups(course_id, fileName, seperator, write); driver = createScorionGroups(groups, course_id); #throws windowserror driver.quit(); self.finish(); def createFile(self): course_id = self.courseVar2.get(); fileName = self.fileVar2.get(); seperator = self.sepVar2.get(); getGroups(course_id, fileName, seperator, True); self.finish(); def split(self): scorFile = self.scorFileName.get(); errFile = self.errFileName.get(); splitGroups(scorFile, errFile); self.finish(); def finish(self): self.progress["mode"] = 'determinate'; self.progress.update_idletasks(); self.progress.stop(); self.progressLabel["text"] = "Finished!"; self.cancelButton["text"] = "Back to menu"; self.closeP6.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP6.bind("<Enter>", self.buttonEnterBG); self.closeP6.bind("<Leave>", self.buttonNormalBG) self.cancelButton.config(command=self.backtomenu); def backtomenu(self): self.scorFileVar.set(""); self.errFileVar.set(""); self.courseVar.set(""); self.courseVar2.set(""); self.fileVar.set(""); self.fileVar2.set(""); self.sepVar.set(","); self.sepVar2.set(","); self.p2.lift(); self.cancelButton.config(text = "cancel", command=exit); self.closeP6.place_forget(); self.progressLabel["text"] = "Working, this might take a couple of minutes..."; self.progress["mode"] = 'indeterminate';
class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): # master window self.master.title("Scraper") # labels l1 = Label( self.master, text= 'Lets do some scraping, fill in the fields and hit search. Then enjoy!', fg="red") l1.grid(column=0, row=0, columnspan=4) l2 = Label(self.master, text="url or list of url's to search:") l2.grid(column=0, row=4) l3 = Label(self.master, text="location to save to:") l3.grid(column=0, row=5) l4 = Label(self.master, text="String to search for:", fg="blue") l4.grid(column=0, row=3) # buttons #b1 = Button(self.master, text="secret", command=self.secret, bg="green", activebackground="orange") #b1.grid(column=0, row=0, sticky=W) b2 = Button(self.master, text="quit", command=self.quit, fg="red", activebackground="red") b2.grid(column=0, row=6, sticky=W, padx=5) b3 = Button(self.master, text="Browse", command=self.browse1, bg="lime", activebackground="tan") b3.grid(column=3, row=4, sticky=E) b4 = Button(self.master, text="Browse", command=self.browse2, bg="lime", activebackground="tan") b4.grid(column=3, row=5, sticky=E) b5 = Button(self.master, text="Search", command=self.search, bg="orange", activebackground="pink") b5.grid(column=3, row=6, sticky=W) # Data Entry self.e1 = Entry(self.master) # default relief is SUNKEN self.e1.grid(column=1, row=4, sticky=(W, E), pady=5, ipady=3) self.e2 = Entry(self.master) self.e2.grid(column=1, row=5, sticky=(W, E), pady=5, ipady=3) self.e3 = Entry(self.master) self.e3.grid(column=1, row=3, sticky=(W, E), pady=5, ipady=3) # Sizegrip self.sg = Sizegrip(self.master).grid(column=999, row=999, sticky=(S, E)) self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) # these make sizegrip work # Progressbar self.pb = Progressbar(self.master, orient=HORIZONTAL, length=200, mode='indeterminate') self.pb.grid(column=1, row=6, sticky=W) # pop-up for file open dialog def browse1(self): fname = askopenfilename(initialdir='C:/Users', title="Browse to file", filetypes=(("Text files", "*.txt"), ("All files", "*.*"))) if fname: try: self.e1.insert( 0, fname) # insert the file path into the dialog box print(fname) except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname) # pop-up for file save dialog def browse2(self): # this gives a dialog that asks for a file name to save and returns the file. It also creates the file in the location given fname = asksaveasfilename(initialdir='C:/Users', title="Browse to file", defaultextension=".txt", filetypes=(("Text files", "*.txt"), ("All files", "*.*"))) if fname: try: self.e2.insert(0, fname) print(fname) except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname) def quit(self): exit() def urlSearch(self, url, logFile, sText): count = 0 with open(logFile, "a") as f: # append to the above created file with urlopen(url) as html: f.write("\n") f.write("Website:\n") f.write(url) f.write("\n") soup = BeautifulSoup(html) # create beautifulsoup object #print("pretty") #print(soup.prettify()) print("") print("original encoding is: %s" % soup.original_encoding) #f.write("original encoding of webpage: \n") #f.write(soup.original_encoding) #f.write("\n") #f.write("\n") print("") #print("find text") print("string to look for:") print(sText) f.write("String to look for: \n") f.write(sText) f.write("\n") f.write("\n") """ # these do the same thing data = soup.find(text=sText) print("data = %s" %data) if data == sText: # print("in if test") #text = soup.getText(sText) print(data) count += 1 # update the counter print("found text") """ data = [] data = soup.find_all(text=sText) print("data = %s" % data) for i in range(0, len(data)): if data[i] == sText: # print("in if test") print(data[i]) count += 1 # update the counter print("found text") print("Text string found %i times" % count) f.write("Text string found %i times" % count) f.write("\n") f.write( "**************************************************************" ) f.write("\n") self.pb.step() self.pb.update_idletasks() print() print("Done") def search(self): self.pb.start(5) # start the progressbar with 5 millisecond interval # get the text out of the entry widget url = self.e1.get() # url or list of url's logLoc = self.e2.get() # location to save to log file to sText = self.e3.get() # string to search for print(url) #print(type(url)) print(sText) print(type(sText)) print(logLoc) # Lets parse the string from the dialog box # This case is if a url is typed directly into the dialog box if url[0] == "h" and url[1] == "t" and url[2] == "t" and url[3] == "p": # print("in if") self.urlSearch(url, logLoc, sText) else: # This case is to support opening a file and getting the url or url's lineCount = 0 with open(url) as f: for lines in f: URL = f.readline() # print(URL) # If there is a empty line in the file pass if URL in ['\n', '\r\n']: print("emptyline found") #pass # if its the end of the file break out of the loop elif URL == '': break else: self.urlSearch(URL, logLoc, sText) lineCount += 1 print("%i lines read" % lineCount) self.pb.stop() # stop the progressbar self.e1.delete(0, END) # delete the text from the entry widget self.e2.delete(0, END) self.e3.delete(0, END) self.master.destroy() # after the search is finished close the window
class RightPanel(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.pack(side=tk.RIGHT, fill=tk.BOTH) self.map_dim = [0, 0] self.param_frame = tk.LabelFrame(self, text="Parameters") self.param_frame.configure(padx=5, pady=5) self.param_frame.pack(fill=tk.X) tk.Label(self.param_frame, text="M :").grid(row=2, column=0, sticky='sw') self.m_scale = tk.Scale(self.param_frame, from_=16, to=128, orient=tk.HORIZONTAL, resolution=16) self.m_scale.grid(row=2, column=2, sticky='nsew', columnspan=2) self.m_scale.set(64) tk.Label(self.param_frame, text="N :").grid(row=3, column=0, sticky='sw') self.n_scale = tk.Scale(self.param_frame, from_=16, to=128, orient=tk.HORIZONTAL, resolution=16) self.n_scale.grid(row=3, column=2, sticky='nsew') self.n_scale.set(64) tk.Label(self.param_frame, text="Detection :").grid(row=4, column=0, sticky='sw') self.combo_detect = tk.ttk.Combobox(self.param_frame, state="readonly") self.combo_detect['values'] = ('Peak Detection', 'OS-CFAR', 'CA-CFAR') self.combo_detect.current(0) self.combo_detect.grid(row=4, column=2, sticky='nsew') self.combo_detect.bind("<<ComboboxSelected>>", self.changeDetectionMode) self.label_thresh = tk.Label(self.param_frame, text="Detection\nThreshold :") self.label_thresh.grid(row=5, column=0, sticky='sw') # self.label_CFAR = tk.Label(self.sim_frame, text="\u03B1 :") # self.label_CFAR.grid(row=5, column=0) # self.label_CFAR.grid_remove() self.detect_thresh = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=-50, to=-150, resolution=10) self.detect_thresh.grid(row=5, column=2, sticky='nsew') self.detect_thresh.set(-90) # self.detect_CFAR = tk.Scale(self.sim_frame, orient=tk.HORIZONTAL, from_=0, to=3, resolution=0.1) # self.detect_CFAR.grid(row=5, column=2) # self.detect_CFAR.set(0.5) # self.detect_CFAR.grid_remove() self.proba_label = tk.Label(self.param_frame, text="Pᶠᵃ [log10]:") self.proba_label.grid(row=6, column=0, sticky='sw') self.proba_label.grid_remove() self.proba_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=-1, to=-10, resolution=1) self.proba_scale.grid(row=6, column=2, sticky='nsew') self.proba_scale.set(-9) self.proba_scale.grid_remove() self.NCFAR_label = tk.Label(self.param_frame, text="Nᶜᶠᵃʳ :") self.NCFAR_label.grid(row=7, column=0, sticky='sw') self.NCFAR_label.grid_remove() self.NCFAR_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=10, to=50, resolution=10) self.NCFAR_scale.grid(row=7, column=2, sticky='nsew') self.NCFAR_scale.set(40) self.NCFAR_scale.grid_remove() self.guard_label = tk.Label(self.param_frame, text="Guard Cells :") self.guard_label.grid(row=8, column=0, sticky='sw') self.guard_label.grid_remove() self.guard_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=6, resolution=2) self.guard_scale.grid(row=8, column=2, sticky='nsew') self.guard_scale.set(2) self.guard_scale.grid_remove() self.kCFAR_label = tk.Label(self.param_frame, text="kᶜᶠᵃʳ :") self.kCFAR_label.grid(row=9, column=0, sticky='sw') self.kCFAR_label.grid_remove() self.kCFAR_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=10, resolution=1) self.kCFAR_scale.grid(row=9, column=2, sticky='nsew') self.kCFAR_scale.set(4) self.kCFAR_scale.grid_remove() tk.Label(self.param_frame, text="AoA\nThreshold :").grid(row=10, column=0, sticky='sw') self.aoa_thresh = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=-10, resolution=1) self.aoa_thresh.grid(row=10, column=2, sticky='nsew') self.aoa_thresh.set(-6) self.sim_frame = tk.LabelFrame(self, text="Simulation") self.sim_frame.configure(padx=5, pady=5) self.sim_frame.pack(fill=tk.X) tk.Label(self.sim_frame, text="Duration [s]:").grid(row=0, column=0, sticky='sw') self.time_scale = tk.Scale(self.sim_frame, from_=1, to=20, orient=tk.HORIZONTAL, resolution=1) self.time_scale.grid(row=0, column=2, sticky='nsew') self.time_scale.set(10) tk.Label(self.sim_frame, text="RDM Freq. [Hz]:").grid(row=1, column=0, sticky='sw') self.rdm_scale = tk.Scale(self.sim_frame, from_=1, to=4, orient=tk.HORIZONTAL, resolution=1) self.rdm_scale.grid(row=1, column=2, sticky='nsew') self.rdm_scale.set(2) self.run_btn = tk.Button(self.sim_frame, text="Run Simulation") self.run_btn['state'] = 'disabled' self.run_btn.grid(row=2, column=2, columnspan=3) self.analysis_frame = tk.LabelFrame(self, text="Analysis") self.analysis_frame.configure(padx=5, pady=5) self.analysis_frame.pack(fill=tk.Y) yScroll = tk.Scrollbar(self.analysis_frame, orient=tk.VERTICAL) self.param_listbox = tk.Listbox(self.analysis_frame, yscrollcommand=yScroll.set, activestyle='none', exportselection=False, height=5) self.param_listbox.grid(row=1, column=0, columnspan=2, sticky='nsew') yScroll.grid(row=1, column=2, sticky='ns') yScroll.config(command=self.param_listbox.yview) self.add_btn = tk.Button(self.analysis_frame, text="Add") self.add_btn.grid(row=2, column=2) self.remove_btn = tk.Button(self.analysis_frame, text="Remove") self.remove_btn['state'] = 'disabled' self.remove_btn.grid(row=2, column=1, sticky='e') tk.Label(self.analysis_frame, text="Nb. of iteration for\neach parameter :").grid( row=3, column=0, sticky='sw') self.run_scale = tk.Scale(self.analysis_frame, from_=10, to=100, orient=tk.HORIZONTAL, resolution=10) self.run_scale.grid(row=3, column=1, sticky='nsew') self.run_scale.set(50) self.analysis_btn = tk.Button(self.analysis_frame, text="Run Analysis") self.analysis_btn['state'] = 'disabled' self.analysis_btn.grid(row=4, column=0, columnspan=2) self.progress_bar = Progressbar(self, orient=tk.HORIZONTAL, mode='determinate') self.progress_bar.pack(fill=tk.X) def setMapDim(self, map_dim): self.map_dim = map_dim def bar(self, value): self.progress_bar['value'] = round(100 * value / self.time_scale.get()) self.progress_bar.update_idletasks() def barAnalysis(self, value): self.progress_bar['value'] = round(100 * value / self.run_scale.get()) self.progress_bar.update_idletasks() def addParam(self, param): if param[2] == "Peak Detection": self.param_listbox.insert( 'end', str(param[2]) + " " + # Detection str(param[0]) + "|" + # N str(param[1]) + "|" + # M str(param[3]) + "|" + # Threshold str(param[4])) # AoA elif param[2] == "OS-CFAR": self.param_listbox.insert( 'end', str(param[2]) + " " + # Detection str(param[0]) + "|" + # N str(param[1]) + "|" + # M str(param[3]) + "|" + # Pfa str(param[4]) + "|" + # Ncfar str(param[5]) + "|" + # Guard cells str(param[6]) + "|" + # kcfar str(param[7])) # AoA else: self.param_listbox.insert( 'end', str(param[2]) + " " + # Detection str(param[0]) + "|" + # N str(param[1]) + "|" + # M str(param[3]) + "|" + # Pfa str(param[4]) + "|" + # Ncfar str(param[5]) + "|" + # Guard cells str(param[6])) # AoA self.param_listbox.select_clear(0, 'end') self.param_listbox.select_set('end') self.param_listbox.event_generate("<<ListboxSelect>>") def removeParam(self, index): self.param_listbox.delete(index) self.param_listbox.select_clear(0, 'end') self.param_listbox.select_set('end') if not self.param_listbox.curselection(): self.remove_btn['state'] = "disabled" def changeDetectionMode(self, event): event.widget.master.focus_set() if self.combo_detect.get() == "Peak Detection": # self.label_CFAR.grid_remove() # self.detect_CFAR.grid_remove() self.proba_label.grid_remove() self.proba_scale.grid_remove() self.NCFAR_label.grid_remove() self.NCFAR_scale.grid_remove() self.guard_label.grid_remove() self.guard_scale.grid_remove() self.kCFAR_label.grid_remove() self.kCFAR_scale.grid_remove() self.label_thresh.grid() self.detect_thresh.grid() elif self.combo_detect.get() == "OS-CFAR": self.label_thresh.grid_remove() self.detect_thresh.grid_remove() # self.label_CFAR.grid() # self.detect_CFAR.grid() self.guard_label.grid() self.guard_scale.grid() self.proba_label.grid() self.proba_scale.grid() self.NCFAR_label.grid() self.NCFAR_scale.grid() self.kCFAR_label.grid() self.kCFAR_scale.grid() else: self.label_thresh.grid_remove() self.detect_thresh.grid_remove() self.kCFAR_label.grid_remove() self.kCFAR_scale.grid_remove() self.guard_label.grid() self.guard_scale.grid() # self.label_CFAR.grid() # self.detect_CFAR.grid() self.proba_label.grid() self.proba_scale.grid() self.NCFAR_label.grid() self.NCFAR_scale.grid() def updateNScale(self, N): if N == 16: self.NCFAR_scale.configure(from_=10, to=10) self.guard_scale.configure(from_=0, to=2) elif N == 32: self.NCFAR_scale.configure(from_=10, to=20) self.guard_scale.configure(from_=0, to=6) elif N == 48: self.NCFAR_scale.configure(from_=10, to=30) self.guard_scale.configure(from_=0, to=6) else: self.NCFAR_scale.configure(from_=10, to=50) self.guard_scale.configure(from_=0, to=6)
class showProgress(): progress=None cancel=None label=None def __init__(self,parent,title='progress',minVal=0,maxVal=100,autoShow=True,autoHide=True,cancelButton=True): self.parent=parent self.title=title self.minVal=minVal self.maxVal=maxVal self.autoHide=autoHide self.cancelButton=cancelButton if autoShow: self.show() def show(self): # Create child top = tkinter.Toplevel(self.parent) top.wm_title(self.title) self.top=top # Remove min/max buttons for child top.resizable(False,False) # no resize in X and Y top.transient(self.parent) # remove max and min buttons for window # Redirect close button in window bar top.protocol('WM_DELETE_WINDOW', self.hide) # Populate child with widgets self.label=tkinter.Label(top,text="0%") self.label.grid(row=0,column=0,pady=12) self.progress = Progressbar(top, orient=HORIZONTAL,length=320,mode='determinate') self.progress.grid(row=1,column=0,padx=12,pady=0) self.cancel = Button(top, text='Cancel', command=self.hide) self.cancel.grid(row=3,column=0,pady=12) if not self.cancelButton: self.cancel["state"] = tkinter.DISABLED # Position child top.update() top.update_idletasks() # Center this child px = self.parent.winfo_rootx() py = self.parent.winfo_rooty() pw = self.parent.winfo_width() ph = self.parent.winfo_height() cw = self.top.winfo_width() ch = self.top.winfo_height() cx = px+(pw-cw)/2 cy = py+(ph-ch)/2 geom = "+%d+%d" % (cx,cy) top.geometry(geom) def hide(self): print ("Hide") self.top.destroy() oldVal=-1 def setProgress(self,val): if val<self.minVal: val=self.minVal if val>self.maxVal: val=self.maxVal pval=0 if val==self.maxVal: pval=100 else: pval=int(100*(val-self.minVal))/(self.maxVal-self.minVal) self.progress['value']=pval self.label['text']=str(pval)+"%" if val==self.maxVal: if self.autoHide: self.hide() else: self.label['text']="100%" self.cancel['text']='OK' self.cancel["state"] = tkinter.NORMAL if pval!=self.oldVal: self.oldVal=pval #print (val,str(pval)+"%") self.label.update() self.label.update_idletasks() self.progress.update() self.progress.update_idletasks() self.top.update() self.top.update_idletasks() def setProgressPerc(self,val): if val<0: val=0 if val>100: val=100 self.progress['value']=val self.label['text']=str(val)+"%" if val==100: if self.autoHide: self.hide() else: self.label['text']="100%" self.cancel['text']='OK' self.cancel["state"] = tkinter.NORMAL if val!=self.oldVal: self.oldVal=val #print (val,str(val)+"%") self.label.update() self.label.update_idletasks() self.progress.update() self.progress.update_idletasks() self.top.update() self.top.update_idletasks()
class Write_num(object): DEFAULT_PEN_SIZE = 10.0 DEFAULT_COLOUR = 'black' def __init__(self): self.root = Tk() self.root.title("Know your Numbers!") self.root.geometry('{}x{}'.format(900, 750)) #self.label = tkinter.Label(self.root, image = icon) #self.label.grid(row = 0, column = 0) self.page = Canvas(self.root, bg='white', width=600, height=600) self.page.grid(row=0, columnspan=5) self.page.config(state="disabled") new_icon = tkinter.PhotoImage(file=r"./Icons/hand.png") self.new_button = Button(self.root, image=new_icon, bg="yellow", command=self.allowDrawing) self.new_button.configure(width=600, height=600, relief=RAISED) self.new_button_window = self.page.create_window( 10, 10, window=self.new_button) self.new_button.grid(row=0, columnspan=5, ipady=20) self.style_bar = ttk.Style() self.style_bar.theme_use('default') self.style_bar.configure("black.Vertical.TProgressbar", background='red', thickness=50, mode="percent") self.progress_var = tkinter.IntVar() self.bar = Progressbar(self.root, length=600, style='black.Vertical.TProgressbar', mode='determinate', var=self.progress_var) self.bar['orient'] = "vertical" self.bar.grid(row=0, column=6) #self.bar["value"] = 0 customFont = tkFont.Font(family='NotoSans', size=50) self.display = Text(self.root, font=customFont, foreground="purple", spacing1=10, spacing2=10, spacing3=10, height=5) self.display.grid(row=0, column=7) self.display.tag_add("center", "1.0") self.display.config(state="disabled") palette_icon = PhotoImage(file=r"./Icons/palette.png") self.color_button = Button(self.root, image=palette_icon, bg='white', command=self.chooseColor) self.color_button.grid(row=1, column=0, ipadx=15, ipady=15, padx=10, pady=10) self.color_button.config(state="disabled") eraser_icon = PhotoImage(file=r"./Icons/eraser.png") self.clear_button = Button(self.root, image=eraser_icon, bg='white', command=self.clear) self.clear_button.grid(row=1, column=2, ipadx=15, ipady=15, padx=10, pady=10) self.clear_button.config(state="disabled") check_icon = PhotoImage(file=r"./Icons/check.png") self.check_button = Button(self.root, image=check_icon, bg='white', command=self.preprocess) self.check_button.grid(row=1, column=4, ipadx=15, ipady=15, padx=10, pady=10) self.check_button.config(state="disabled") self.img_filename = "hand_num" #call model self.model = test.loadModel() #print("______Model loaded_________") self.setup() self.root.mainloop() def setup(self): self.x1 = None self.y1 = None self.line_width = self.DEFAULT_PEN_SIZE self.color = self.DEFAULT_COLOUR self.clear_on = False self.page.bind('<B1-Motion>', self.write) #button-1 is left click self.page.bind('<ButtonRelease-1>', self.penup) def allowDrawing(self): self.new_button.grid_remove() self.new_button["state"] = DISABLED self.color_button.config(state="normal") self.clear_button.config(state="normal") self.check_button.config(state="normal") #print("here1") global retry self.givenNum = numberGeneratorChecker.obtainNumber(retry) retry = 0 #print("here2") self.page.config(state="normal") def write(self, event): self.line_width = self.DEFAULT_PEN_SIZE write_color = self.color if self.x1 and self.y1: self.page.create_line(self.x1, self.y1, event.x, event.y, width=self.line_width, fill=write_color, capstyle=ROUND, smooth=TRUE, splinesteps=36) self.x1 = event.x self.y1 = event.y def chooseColor(self): self.clear_on = False self.color = askcolor(color=self.color)[1] def clear(self): self.page.delete("all") def preprocess(self): self.page.config(state="disabled") self.color_button.config(state="disabled") self.clear_button.config(state="disabled") self.check_button.config(state="disabled") img = self.page.postscript(file=self.img_filename + '.eps') img = Image.open(self.img_filename + '.eps') img.save(self.img_filename + '.png', 'png') img = cv2.imread(self.img_filename + '.png', cv2.IMREAD_GRAYSCALE) #grayscaling img = cv2.resize( 255 - img, (28, 28), interpolation=cv2.INTER_AREA) #invert and shrink to 28*28 (thresh, img) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) #thresholding try: while np.sum( img[0] ) == 0: #cropping will give traceback if canvas blank. img = img[1:] while np.sum(img[:, 0]) == 0: img = np.delete(img, 0, 1) while np.sum(img[-1]) == 0: img = img[:-1] while np.sum(img[:, -1]) == 0: img = np.delete(img, -1, 1) rows, cols = img.shape if rows > cols: #fit to 20*20, adjust for aspect ratio factor = 20.0 / rows rows = 20 cols = int(round(cols * factor)) img = cv2.resize(img, (cols, rows)) else: factor = 20.0 / cols cols = 20 rows = int(round(rows * factor)) img = cv2.resize(img, (cols, rows)) colsPadding = (int(math.ceil( (28 - cols) / 2.0)), int(math.floor( (28 - cols) / 2.0))) #padding to get 28*28 rowsPadding = (int(math.ceil( (28 - rows) / 2.0)), int(math.floor((28 - rows) / 2.0))) img = np.lib.pad(img, (rowsPadding, colsPadding), 'constant') shift_x, shift_y = self.getBestShift(img) #centering in 28*28 shifted = self.shift(img, shift_x, shift_y) img = shifted cv2.imwrite(self.img_filename + '.png', img) img = img.flatten() / 255.0 #name = "imgdata" + str(datetime.now()) + ".csv" np.savetxt("imgdata.csv", img, delimiter=",") #pass csv to Mugdha arr = test.testPNG(self.model, "imgdata.csv", self.givenNum) self.modelAccuracy = arr[0] if self.modelAccuracy == 0: self.accuracy = 0 if self.modelAccuracy == 1: numProb = arr[1] #print("self.accuracy is :", numProb) if numProb < 0.994 and numProb >= 0.75: numProb = 0.75 numProb = int(numProb * 100) #will return accuracy self.accuracy = numProb #print("self.accuracy is :", self.accuracy) self.showScore() self.bar.update_idletasks() #shrunk = np.array(shrunk) #Image.fromarray(shrunk).save(self.img_filename + '.png') #Titles =["Original", "Shrunk"] #images =[image, shrunk] #count = 2 #for i in range(count): # plt.subplot(2, 2, i + 1) # plt.title(Titles[i]) # plt.imshow(images[i]) #plt.show() except: #canvas was blank when check button clicked. #print("In except") numberGeneratorChecker.retryInstruction() self.reset() def getBestShift(self, img): #get adjustment for center of mass cy, cx = ndimage.measurements.center_of_mass(img) rows, cols = img.shape shift_x = np.round(cols / 2.0 - cx).astype(int) shift_y = np.round(rows / 2.0 - cy).astype(int) return shift_x, shift_y def shift(self, img, sx, sy): #shift according to center of mass rows, cols = img.shape M = np.float32([[1, 0, sx], [0, 1, sy]]) shifted = cv2.warpAffine(img, M, (cols, rows)) return shifted def showScore(self): k = 0 if self.accuracy < 50: score = 1 else: (quo, rem) = divmod(self.accuracy, 10) if rem == 0: score = self.accuracy // 10 else: score = (self.accuracy // 10) + 1 for i in range(0, score + 1): self.progress_var.set(k) #print("STEP", i) k += 10 time.sleep(0.1) if self.bar["value"] > 80: self.style_bar.configure("black.Vertical.TProgressbar", background='lime green', thickness=50, mode="percent") elif self.bar["value"] > 60: self.style_bar.configure("black.Vertical.TProgressbar", background='yellow', thickness=50, mode="percent") else: self.style_bar.configure("black.Vertical.TProgressbar", background='red', thickness=50, mode="percent") self.bar.update_idletasks() #print(self.bar["value"]) if self.bar["value"] > 40: self.devauni, self.numName = convtodeva.obtaindeva(self.givenNum) self.displayNum() else: global retry retry = 1 numberGeneratorChecker.retryInstruction() self.reset() def displayNum(self): self.display.config(state="normal") #devauni = b'\u096A' #self.display.insert("1.0", self.devauni.decode('unicode-escape')) #num_name = "\nfour" devaimg = PhotoImage(file=r"./DevaDigits/" + str(self.givenNum) + ".png") self.display.image_create(END, image=devaimg) self.display.insert(END, self.numName) self.display.config(state="disabled") self.root.after(4000, self.reset()) #time.sleep(4) #self.reset() def penup(self, event): self.x1, self.y1 = None, None def reset(self): #print("resetting") #self.display.config(state = "normal") self.progress_var.set(0) self.bar.update_idletasks() self.page.config(state="normal") self.page.delete("all") self.page.config(state="disabled") self.display.config(state="normal") self.display.delete(1.0, END) self.display.config(state="disabled") self.new_button.config(state=NORMAL) self.new_button.grid()
class RightPanel(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.pack(side=tk.RIGHT, fill=tk.BOTH) self.map_dim = [0, 0] self.param_frame = tk.LabelFrame(self, text="Parameters") self.param_frame.configure(padx=5, pady=5) self.param_frame.grid_columnconfigure(1, weight=1) self.param_frame.pack(fill=tk.X) tk.Label(self.param_frame, text="M :").grid(row=2, column=0, sticky='sw') self.m_scale = tk.Scale(self.param_frame, from_=16, to=128, orient=tk.HORIZONTAL, resolution=16) self.m_scale.grid(row=2, column=1, sticky='nsew') self.m_scale.set(64) tk.Label(self.param_frame, text="N :").grid(row=3, column=0, sticky='sw') self.n_scale = tk.Scale(self.param_frame, from_=16, to=128, orient=tk.HORIZONTAL, resolution=16) self.n_scale.grid(row=3, column=1, sticky='nsew') self.n_scale.set(64) tk.Label(self.param_frame, text="Detection :").grid(row=4, column=0, sticky='sw') self.combo_detect = tk.ttk.Combobox(self.param_frame, state="readonly") self.combo_detect['values'] = ('Peak Detection', 'CA-CFAR') #'OS-CFAR' self.combo_detect.current(0) self.combo_detect.grid(row=4, column=1, sticky='nsew') self.combo_detect.bind("<<ComboboxSelected>>", self.detectionEvent) self.label_thresh = tk.Label(self.param_frame, text="Detection\nThreshold :") self.label_thresh.grid(row=5, column=0, sticky='sw') self.detect_thresh = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=-50, to=-150, resolution=10) self.detect_thresh.grid(row=5, column=1, sticky='nsew') self.detect_thresh.set(-90) self.proba_label = tk.Label(self.param_frame, text="Pᶠᵃ [log10]:") self.proba_label.grid(row=6, column=0, sticky='sw') self.proba_label.grid_remove() self.proba_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=-1, to=-10, resolution=1) self.proba_scale.grid(row=6, column=1, sticky='nsew') self.proba_scale.set(-9) self.proba_scale.grid_remove() self.proba_btn = tk.Button(self.param_frame, text="\u2193") self.proba_btn.grid(row=6, column=2, sticky='s') self.proba_btn.grid_remove() self.NCFAR_label = tk.Label(self.param_frame, text="Nᶜᶠᵃʳ :") self.NCFAR_label.grid(row=7, column=0, sticky='sw') self.NCFAR_label.grid_remove() self.NCFAR_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=10, to=50, resolution=10) self.NCFAR_scale.grid(row=7, column=1, sticky='nsew') self.NCFAR_scale.set(20) self.NCFAR_scale.grid_remove() self.NCFAR_btn = tk.Button(self.param_frame, text="\u2193") self.NCFAR_btn.grid(row=7, column=2, sticky='s') self.NCFAR_btn.grid_remove() self.guard_label = tk.Label(self.param_frame, text="Guard Cells :") self.guard_label.grid(row=8, column=0, sticky='sw') self.guard_label.grid_remove() self.guard_scale = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=6, resolution=2) self.guard_scale.grid(row=8, column=1, sticky='nsew') self.guard_scale.set(2) self.guard_scale.grid_remove() self.guard_btn = tk.Button(self.param_frame, text="\u2193") self.guard_btn.grid(row=8, column=2, sticky='s') self.guard_btn.grid_remove() self.pfa_var = tk.StringVar() self.pfa_label = tk.Label(self.param_frame, textvariable=self.pfa_var) self.pfa_label.grid(row=11, column=1, sticky='nsew') self.pfa_label.grid_remove() tk.Label(self.param_frame, text="AoA\nThreshold :").grid(row=12, column=0, sticky='sw') self.aoa_thresh = tk.Scale(self.param_frame, orient=tk.HORIZONTAL, from_=0, to=-10, resolution=1) self.aoa_thresh.grid(row=12, column=1, sticky='nsew') self.aoa_thresh.set(-6) self.aoa_btn = tk.Button(self.param_frame, text="\u2193") self.aoa_btn.grid(row=12, column=2, sticky='e') self.range_check = tk.IntVar() self.range_check.set(1) self.range_btn = tk.Checkbutton(self.param_frame, text="Range leakage", variable=self.range_check, onvalue=1, offvalue=0) self.range_btn.grid(row=13, column=1, sticky='e') self.sim_frame = tk.LabelFrame(self, text="Time simulation") self.sim_frame.configure(padx=5, pady=5) self.sim_frame.grid_columnconfigure(1, weight=1) self.sim_frame.pack(fill=tk.X) tk.Label(self.sim_frame, text="Duration [s]:").grid(row=0, column=0, sticky='sw') self.time_scale = tk.Scale(self.sim_frame, from_=1, to=20, orient=tk.HORIZONTAL, resolution=1) self.time_scale.grid(row=0, column=1, sticky='nsew') self.time_scale.set(10) tk.Label(self.sim_frame, text="RDM Freq. [Hz]:").grid(row=1, column=0, sticky='sw') self.rdm_scale = tk.Scale(self.sim_frame, from_=1, to=4, orient=tk.HORIZONTAL, resolution=1) self.rdm_scale.grid(row=1, column=1, sticky='nsew') self.rdm_scale.set(2) self.run_btn = tk.Button(self.sim_frame, text="Run Simulation") self.run_btn['state'] = 'disabled' self.run_btn.grid(row=2, column=1, columnspan=3) self.analysis_frame = tk.LabelFrame(self, text="Instant analysis") self.analysis_frame.configure(padx=5, pady=5) self.analysis_frame.pack(fill=tk.Y) self.analysis_frame.grid_columnconfigure(1, weight=1) style = ttk.Style() style.configure("mystyle.Treeview", background='white') style.configure("mystyle.Treeview.Heading", font=('Calibri', 10, 'bold'), background='lightgray') self.yScroll_1 = tk.Scrollbar(self.analysis_frame, orient=tk.VERTICAL) self.thresh_tree = ttk.Treeview(self.analysis_frame, selectmode='extended', yscrollcommand=self.yScroll_1.set, style="mystyle.Treeview") self.yScroll_1.config(command=self.thresh_tree.yview) self.thresh_tree.grid(row=1, column=0, columnspan=2) self.yScroll_1.grid(row=1, column=2, sticky='ns') self.yScroll_2 = tk.Scrollbar(self.analysis_frame, orient=tk.VERTICAL) self.CACFAR_tree = ttk.Treeview(self.analysis_frame, selectmode='extended', yscrollcommand=self.yScroll_2.set, style="mystyle.Treeview") self.yScroll_2.config(command=self.CACFAR_tree.yview) self.CACFAR_tree.grid(row=1, column=0, columnspan=2) self.yScroll_2.grid(row=1, column=2, stick='ns') self.CACFAR_tree.grid_remove() self.yScroll_2.grid_remove() self.configureTrees() self.add_btn = tk.Button(self.analysis_frame, text="Add") self.add_btn.grid(row=2, column=2) self.remove_btn = tk.Button(self.analysis_frame, text="Remove") self.remove_btn['state'] = 'disabled' self.remove_btn.grid(row=2, column=1, sticky='e') self.clear_btn = tk.Button(self.analysis_frame, text="Clear") self.clear_btn.grid(row=2, column=0, sticky='w') tk.Label(self.analysis_frame, text="Nb. of iteration for\neach parameter :").grid(row=3, column=0, sticky='sw') self.run_scale = tk.Scale(self.analysis_frame, from_=10, to=1000, orient=tk.HORIZONTAL, resolution=10) self.run_scale.grid(row=3, column=1, sticky='nsew') self.run_scale.set(50) self.analysis_btn = tk.Button(self.analysis_frame, text="Run Analysis") self.analysis_btn['state'] = 'disabled' self.analysis_btn.grid(row=4, column=0, columnspan=2) self.progress_bar = Progressbar(self, orient=tk.HORIZONTAL, mode='determinate') self.progress_bar.pack(fill=tk.X) def configureTrees(self): # Threshold : self.thresh_tree['columns'] = ('N', 'M', 'thresh', 'AoA', 'RL') self.thresh_tree['show'] = 'headings' self.thresh_tree['height'] = 7 self.thresh_tree['selectmode'] = None self.thresh_tree.column('N', width=30, anchor='c', stretch=False) self.thresh_tree.column('M', width=30, anchor='c', stretch=False) self.thresh_tree.column('thresh', width=90, anchor='c', stretch=False) self.thresh_tree.column('AoA', width=80, anchor='c', stretch=False) self.thresh_tree.column('RL', width=80, anchor='c', stretch=False) self.thresh_tree.heading("N", text="N") self.thresh_tree.heading("M", text="M") self.thresh_tree.heading("thresh", text="Detec. Thresh.") self.thresh_tree.heading("AoA", text="AoA Thresh.") self.thresh_tree.heading('RL', text="Range Leak.") # CA-CFAR self.CACFAR_tree['columns'] = ('N', 'M', 'pfa', 'NCFAR', 'guard', 'AoA', 'RL') self.CACFAR_tree['show'] = 'headings' self.CACFAR_tree['height'] = 7 self.CACFAR_tree['selectmode'] = None self.CACFAR_tree.column('N', width=30, anchor='c') self.CACFAR_tree.column('M', width=30, anchor='c') self.CACFAR_tree.column('pfa', width=30, anchor='c') self.CACFAR_tree.column('NCFAR', width=40, anchor='c') self.CACFAR_tree.column('guard', width=40, anchor='c') self.CACFAR_tree.column('AoA', width=80, anchor='c') self.CACFAR_tree.column('RL', width=80, anchor='c') self.CACFAR_tree.heading('N', text='N') self.CACFAR_tree.heading('M', text='M') self.CACFAR_tree.heading('pfa', text='Pfa') self.CACFAR_tree.heading('NCFAR', text='Ncfar') self.CACFAR_tree.heading('guard', text='Guard') self.CACFAR_tree.heading('AoA', text='AoA Thresh.') self.CACFAR_tree.heading('RL', text='Range Leak.') def setMapDim(self, map_dim): self.map_dim = map_dim def bar(self, value): self.progress_bar['value'] = round(100 * value / self.time_scale.get()) self.progress_bar.update_idletasks() def barAnalysis(self, value): self.progress_bar['value'] = round(100 * value / self.run_scale.get()) self.progress_bar.update_idletasks() def addParam(self, param): if param['detect'] == "Peak Detection": self.thresh_tree.insert(parent='', index='end', iid=param['idx'], values=(param['N'], param['M'], param['thresh'], param['AoA'], param['RL'])) else: self.CACFAR_tree.insert(parent='', index='end', iid=param['idx'], values=(param['N'], param['M'], param['pfa'], param['NCFAR'], param['guard'], param['AoA'], param['RL'])) self.remove_btn['state'] = "normal" def removeParam(self, items): detection_type = self.combo_detect.get() if detection_type == "Peak Detection": for item in items: self.thresh_tree.delete(item) if len(self.thresh_tree.get_children()) == 0: self.remove_btn['state'] = "disabled" else: for item in items: self.CACFAR_tree.delete(item) if len(self.CACFAR_tree.get_children()) == 0: self.remove_btn['state'] = "disabled" def detectionEvent(self, event): event.widget.master.focus_set() self.changeDetectionMode() def changeDetectionMode(self): if self.combo_detect.get() == "Peak Detection": if len(self.thresh_tree.get_children()) > 0: self.remove_btn['state'] = "normal" else: self.remove_btn['state'] = "disabled" self.yScroll_2.grid_remove() self.CACFAR_tree.grid_remove() self.yScroll_1.grid() self.thresh_tree.grid() self.proba_label.grid_remove() self.proba_scale.grid_remove() self.proba_btn.grid_remove() self.NCFAR_label.grid_remove() self.NCFAR_scale.grid_remove() self.NCFAR_btn.grid_remove() self.guard_label.grid_remove() self.guard_scale.grid_remove() self.guard_btn.grid_remove() self.pfa_label.grid_remove() self.label_thresh.grid() self.detect_thresh.grid() else: if len(self.CACFAR_tree.get_children()) > 0: self.remove_btn['state'] = "normal" else: self.remove_btn['state'] = "disabled" self.yScroll_1.grid_remove() self.thresh_tree.grid_remove() self.yScroll_2.grid() self.CACFAR_tree.grid() self.label_thresh.grid_remove() self.detect_thresh.grid_remove() self.pfa_label.grid_remove() self.guard_label.grid() self.guard_scale.grid() self.guard_btn.grid() self.proba_label.grid() self.proba_scale.grid() self.proba_btn.grid() self.NCFAR_label.grid() self.NCFAR_scale.grid() self.NCFAR_btn.grid() def updateNScale(self, N): if N == 16: self.NCFAR_scale.configure(from_=10, to=10) self.guard_scale.configure(from_=0, to=2) elif N == 32: self.NCFAR_scale.configure(from_=10, to=20) self.guard_scale.configure(from_=0, to=6) elif N == 48: self.NCFAR_scale.configure(from_=10, to=30) self.guard_scale.configure(from_=0, to=6) else: self.NCFAR_scale.configure(from_=10, to=50) self.guard_scale.configure(from_=0, to=6) # ------ # GET def getNM(self): return self.n_scale.get(), self.m_scale.get() def getDetectionMode(self): return self.combo_detect.get() def getDetectionThreshold(self): return self.detect_thresh.get() def getPfa(self): return self.proba_scale.get() def getNCFAR(self): return self.NCFAR_scale.get() def getGuardCells(self): return self.guard_scale.get() def getAngleThreshold(self): return self.aoa_thresh.get() def getRangeLeak(self): return self.range_check.get() == 1
def simulation(): root = Tk() pb = Progressbar(root, orient="horizontal", length=200, mode="indeterminate") pb.pack() pb.start() B_T = w1.get() h_stars = w2.get() r_stars = w3.get() h_ISM = w4.get() r_ISM = w5.get() n_0 = w6.get() nphotons = 100000 #Replace the old .param file with a new one with the entered values with open('test_dustsimulation_original.param') as g: lines = list(g) h = open('test_dustsimulation.param', 'w') for i in range(0, len(lines)): if i == 12: h.write(' B_over_T: ' + str(B_T) + '\n') elif i == 13: h.write(' h_stars: ' + str(h_stars) + ' kpc\n') elif i == 14: h.write(' r_stars: ' + str(r_stars) + ' kpc\n') elif i == 16: h.write(' h_ISM: ' + str(h_ISM) + ' kpc\n') elif i == 18: h.write(' r_ISM: ' + str(r_ISM) + ' kpc\n') elif i == 17: h.write(' n_0: ' + str(n_0) + ' cm^-3\n') elif i == 28: h.write('number of photons: ' + str(nphotons) + '\n') else: h.write(lines[i]) h.close() pb.update_idletasks() pb.update() #Input this new file into the testDustSimulation program and compile os.system(codepath + filename) #Input the created binary file, and plot as an image image = np.fromfile("test_dustsimulation_output.dat", dtype=np.float64) image = image.reshape((200, 200)) fig, ax = plt.subplots() ax.matshow(np.transpose(image), cmap='Greys_r') # ax.matshow(np.transpose(image), cmap=plt.cm.bBu) plt.text(5, 60, "B_T =" + str(B_T) + '\n' + "h_stars =" + str(h_stars) + " kpc" + '\n' + "r_stars =" + str(r_stars) + " kpc" + '\n' + "h_ISM =" + str(h_ISM) + " kpc" + '\n' + "r_ISM =" + str(r_ISM) + " kpc" + '\n' + "n0 =" + str(n_0) + " cm^-3", color='w') tick_locs_x = [0, 100, 200] tick_locs_y = [0, 100, 200] xtick_lbls = ['-12.1kpc', '0', '12.1kpc'] ytick_lbls = ['-12.1kpc', '0', '12.1kpc'] plt.xticks(tick_locs_x, xtick_lbls, rotation=0, fontsize=10) plt.yticks(tick_locs_y, ytick_lbls, rotation=0, fontsize=10) plt.show()