Ejemplo n.º 1
0
class PopupScrolledText(PopupWindow):
    """
    Scrolled text output window with 'Save As...'
    """

    def __init__(self, title="", kind="", iconfile=None, var=None):
        PopupWindow.__init__(self, title=title, kind=kind, iconfile=iconfile)
        if var:
            self._var = var
        else:
            self._var = BooleanVar()
        self._var.trace_variable("w", self._visibility_control)
        self._text = ScrolledText(self)
        self._text.pack()
        self._text.config(font=FONT)
        self._make_menu()
        self._visibility_control()

    def on_close(self, *args):
        self._var.set(False)

    def _visibility_control(self, *args):
        if self._var.get():
            self.deiconify()
        else:
            self.withdraw()

    def _make_menu(self):
        topmenu = Menu(self)
        self.config(menu=topmenu)
        file = Menu(topmenu, tearoff=0)
        file.add_command(label="Save as...", command=self.on_save_as)
        file.add_command(label="Hide", command=self.on_close)
        topmenu.add_cascade(label="File", menu=file)
        edit = Menu(topmenu, tearoff=0)
        edit.add_command(label="Clear text", command=self.on_clear)
        topmenu.add_cascade(label="Edit", menu=edit)

    def on_save_as(self):
        filename = asksaveasfilename()
        if filename:
            alltext = self.gettext()
            f = open(filename, "w")
            f.write(alltext)
            f.close()

    def on_clear(self):
        self._text.delete("0.0", END)
        self._text.update()

    def gettext(self):
        return self._text.get("1.0", END + "-1c")

    def hide(self):
        self._var.set(False)

    def show(self):
        self._var.set(True)
class GuiOutput:
    def __init__(self, parent=None):
        self.text = None
        if parent: self.popupnow(parent)         # popup now or on first write
    def popupnow(self, parent=None):             # in parent now, Toplevel later
        if self.text: return
        self.text = ScrolledText(parent or Toplevel())
        self.text.config(font=('courier', 9, 'normal'))
        self.text.pack()
    def write(self, text):
        self.popupnow()
        self.text.insert(END, str(text))
        self.text.see(END)
        self.text.update()
    def writelines(self, lines):                 # lines already have '\n'
        for line in lines: self.write(line)      # or map(self.write, lines)
class GuiOutput:
    def __init__(self, parent=None):
        self.text = None
        if parent: self.popupnow(parent)  # popup now or on first write

    def popupnow(self, parent=None):  # in parent now, Toplevel later
        if self.text: return
        self.text = ScrolledText(parent or Toplevel())
        self.text.config(font=('courier', 9, 'normal'))
        self.text.pack()

    def write(self, text):
        self.popupnow()
        self.text.insert(END, str(text))
        self.text.see(END)
        self.text.update()

    def writelines(self, lines):  # lines already have '\n'
        for line in lines:
            self.write(line)  # or map(self.write, lines)
Ejemplo n.º 4
0
class GuiOutput:
    def __init__(self, name,parent=None):
        self.text = None
        self.titleName = name
        if parent: self.popupnow(name,parent)         # popup now or on first write
    def popupnow(self,name,parent=None):             # in parent now, Toplevel later
        if self.text: return
        newTopLevel = Toplevel()
        self.text = ScrolledText(parent or newTopLevel)
        newTopLevel.title(name)
        self.text.config(font=('courier', 9, 'normal'))
        #if it is a toplevel textbox, set its title.
        self.text.pack()
    def write(self, text):
        self.popupnow(self.titleName)
        #if len(self.text.get("1.0")) > 1024:
        #    self.text.delete("1.0",END)
        self.text.insert(END, str(text))
        self.text.see(END)
        self.text.update()
    def writelines(self, lines):                 # lines already have '\n'
        for line in lines: self.write(line)      # or map(self.write, lines)
    def flush(self):
        pass
Ejemplo n.º 5
0
    st.configure(font='TkFixedFont')

    # Make the scroll window resizing...
    tk.Grid.rowconfigure(window, 4, weight=1)
    tk.Grid.columnconfigure(window, 0, weight=1)
    st.grid(row=4, column=0, columnspan=2, sticky="nswe", pady=5, padx=5)

    # Create textLogger
    text_handler = TextHandler(st)

    # Add the handler to logger
    logger = logging.getLogger()
    logger.addHandler(text_handler)
    #set level to print out all. Otherwise this will ignore the debug an info prints.
    logger.root.setLevel(logging.NOTSET)
    st.update()

    setWindowHeight = outputGroupFrame.winfo_height()
    setWindowHeight += lbl.winfo_height()
    setWindowHeight += fNameEntry.winfo_height()
    setWindowHeight += st.winfo_height()

    mystring = str(st.winfo_width() + 25) + "x" + str(setWindowHeight + 22)
    window.geometry(mystring)

    window.update()
    window.mainloop()

else:
    writeFileHeader(creoLogicalFileName)
    #------------------------------------------------------------------------------
Ejemplo n.º 6
0
class Dialog(ui.Dialog):
    def __init__(self, frame=None):
        self.parent_frame = frame  # set the parent frame
        self.confirm_frame = None
        self.make_change = False
        self.new_line = u""
        self.status_text = u""
        self.make_silent = False
        self.cancel = False

        # set screen position...
        x = 0
        y = 0
        ##x = config.get('status_x',0)
        ##y = config.get('status_y',0)
        ##if x and y:
        ##    self.parent_frame.geometry("+%d+%d" % (int(x),int(y)))

        # create a status message widget and bind it to the parent...
        # self.status_text = ScrolledText(self.parent_frame, height=20, width=80, state=DISABLED)
        # self.status_text.pack()
        self.status_text = ScrolledText(self.parent_frame, wrap=WORD, pady=2, padx=3, state=DISABLED)
        self.status_text.pack(fill=BOTH, expand=Y)
        self.parent_frame.protocol("WM_DELETE_WINDOW", self.destroy)
        self.parent_frame.bind("<Escape>", self.destroy)
        self.parent_frame.bind("<Configure>", self.save_pos)
        self.status_text.update()

    def confirm_change(self, old_line, new_line, old_tuple=(), new_tuple=(), filepath=""):
        self.confirm_frame = Tkinter.Toplevel(self.parent_frame, padx=10, pady=10)
        # self.confirm_frame.grid(padx=10,pady=10)

        self.confirm_frame.protocol("WM_DELETE_WINDOW", self.confirm_decline)

        # set screen position...
        ##x = config.get('dialog_x', (self.parent_frame.winfo_rootx() + 50))
        ##y = config.get('dialog_y', (self.parent_frame.winfo_rooty() + 50))
        x = self.parent_frame.winfo_rootx() + 50
        y = self.parent_frame.winfo_rooty() + 50
        if x and y:
            self.confirm_frame.geometry("+%s+%s" % (x, y))

        # bind enter to ok and escape to cancel buttons...
        self.confirm_frame.bind("<Return>", self.confirm_accept)
        self.confirm_frame.bind("<Escape>", self.confirm_decline)
        self.confirm_frame.bind("<Configure>", self.save_pos)
        # make the new dialog a part of the parent...
        self.confirm_frame.transient(self.parent_frame)
        # focus onto the dialog...
        self.confirm_frame.focus_set()

        label = Tkinter.Label(self.confirm_frame, text=filepath)
        label.pack()

        label = Tkinter.Label(self.confirm_frame, text="Change:")
        # label.grid(row=row_i, column=0, sticky=W)
        label.pack()

        # entry = Tkinter.Text(self.confirm_frame, width=75, height=5)
        # entry = ScrolledText(self.confirm_frame, width=75, height=5)
        entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3)
        entry.insert(Tkinter.INSERT, old_line.encode("utf-8"))
        # highlight the text to be changed...
        if len(old_tuple) == 2:
            entry.tag_add("found", "1.%s" % (old_tuple[0]), "1.%s+%sc" % (old_tuple[0], old_tuple[1] - old_tuple[0]))
            entry.tag_config("found", foreground="red")

        entry.config(state=DISABLED)
        entry.pack(fill=BOTH, expand=Y)

        label = Tkinter.Label(self.confirm_frame, text="To:")
        label.pack()

        self.new_entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3)
        self.new_entry.insert(Tkinter.INSERT, new_line.encode("utf-8"))
        # highlight the text to be changed...
        if len(new_tuple) == 2:
            self.new_entry.tag_add(
                "found", "1.%s" % (new_tuple[0]), "1.%s+%sc" % (new_tuple[0], new_tuple[1] - new_tuple[0])
            )
            self.new_entry.tag_config("found", foreground="red")

        self.new_entry.config(state=DISABLED)
        self.new_entry.pack(fill=BOTH, expand=Y)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes", command=self.confirm_accept, default=ACTIVE)
        # btnDisplay.grid(row=row_i, column=0)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="No", command=self.confirm_decline)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Cancel", command=self.confirm_cancel)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes to All", command=self.confirm_silence)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        self.confirm_frame.update()
        try:
            self.parent_frame.wait_window(self.confirm_frame)
        except Tkinter.TclError:
            # sometimes the wait_window fails, I'm not sure why, but it seems to be
            # safe to just ignore it *shrug*
            pass

        self.confirm_frame = None

    def confirm_silence(self):
        self.make_change = True
        self.make_silent = True
        self.clean_up()

    def confirm_cancel(self):
        self.make_change = False
        self.cancel = True
        self.clean_up()

    def confirm_accept(self):
        # self.new_line = self.new_entry.get(1.0, END)
        self.make_change = True
        self.clean_up()

    def confirm_decline(self):
        self.make_change = False
        self.clean_up()

    def clean_up(self, event=None):
        self.save_pos()
        # print self.screen_pos_x,self.screen_pos_y
        self.parent_frame.focus_set()
        self.confirm_frame.destroy()

    def destroy(self, event=None):
        self.parent_frame.destroy()

    def save_pos(self, event=None):
        return
        ## save the screen position of the dialog box
        # if self.confirm_frame:
        # try:
        # config.add('dialog_x',(self.confirm_frame.winfo_rootx() - 4))
        # config.add('dialog_y',(self.confirm_frame.winfo_rooty() - 30))
        # except:
        # pass

        ## save the status box's position
        # if self.parent_frame:
        # try:
        # config.add('status_x',self.parent_frame.winfo_rootx() - 4)
        # config.add('status_y',self.parent_frame.winfo_rooty() - 30)
        # except:
        # pass

    def update(self, msg):
        # if the window no longer exists, its text can't be updated
        try:
            self.status_text.config(state=NORMAL)
            # Add the new message
            self.status_text.insert(END, msg.encode("utf-8") + os.linesep)
            # Scroll down to the bottom again
            self.status_text.see(END)
            # Make the display uneditable
            self.status_text.config(state=DISABLED)
            self.status_text.update()
        except:
            pass
Ejemplo n.º 7
0
class SourceEditor:
    def __init__(self,central,name,bodyTopNode,specTopNode):
        self.dirty = False
        self.central = central
        self.name = name
        self.toplevel = Toplevel()
        self.toplevel.title(name)
        self.pw = Pmw.PanedWidget(self.toplevel, orient='vertical')

        specpane = self.pw.add("spec")
        bodypane = self.pw.add("body")
        self.specText = ScrolledText(specpane,font=("monaco",10),height=5,background=Colors.background)
        self.specText.pack(expand=YES,fill=BOTH)
        self.bodyText = ScrolledText(bodypane,font=("monaco",10),height=15,background=Colors.background)
        self.bodyText.pack(expand=YES,fill=BOTH)        
        self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText}
        self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode}
        Widget.bind(self.bodyText,'<Any-KeyPress>',self.setDirty)
        Widget.bind(self.specText,'<Any-KeyPress>',self.setDirty)
        self.popup = Menu(self.toplevel,tearoff=0)
        self.popup.add_command(label="Dismiss", command=self.nothing)
        self.popup.add_command(label="Diagram", command=self.goDiagram)
        self.popup.add_command(label="Abort", command=self.abort)
        self.popup.add_command(label="Accept", command=self.accept)
        self.popup.add_command(label="Recolor", command=self.recolor)        
        def popupMenu(event):
            self.popup.post(event.x_root,event.y_root)
        self.toplevel.bind('<Button-3>', popupMenu)
        self.pw.pack(expand=YES,fill=BOTH)
        self.toplevel.protocol("WM_DELETE_WINDOW",self.central.doQuit)
        self.refresh()
    def nothing(self): pass
    def setClean(self):
        if self.dirty:
            self.dirty = False
            self.toplevel.title(self.name)
            self.central.unlockGraphics(self.name)
    def setDirty(self,event):
        if event.keysym in ['Shift_L', 'Shift_R', 'Alt_L', 'Alt_R', 'Win_L', 'Win_R']:
            return 
        if not self.dirty:
            self.dirty = True
            self.toplevel.title(self.name+"*")
            self.central.lockGraphics(self.name)
    def abort(self):
        if self.dirty:
            self.setClean()
            self.setSource()
    def getSource(self):
        return (self.specText.get("1.0",END),
                self.bodyText.get("1.0",END))
    def accept(self):
        if self.dirty:
            self.bodyText.config(cursor="watch")
            self.specText.config(cursor="watch")
            self.bodyText.update() # so that the cursor will show
            self.specText.update()
            self.central.update(self.name, self.specText.get("1.0",END),
                                self.bodyText.get("1.0",END),saveOutput=False)
            self.central.setChanged(self.name)
            self.setClean()
            self.bodyText.config(cursor="xterm")
            self.specText.config(cursor="xterm")
    def recolor(self):
        stext,btext = self.getSource()
        self.colorize(self.specText,stext)
        self.colorize(self.bodyText,btext)
    def show(self, specTopNode, bodyTopNode):
        self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText}
        self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode}        
        self.setSource()
    def setSource(self):
        oldScroll,dummy = self.specText.yview()
        self.specText.delete('1.0',END)
        stext = self.textMap[self.specText].regen(forDisplay=True)
        self.specText.insert(END,stext)
        self.colorize(self.specText,stext)
        self.specText.yview("moveto", oldScroll)

        oldScroll,dummy = self.bodyText.yview()
        self.bodyText.delete('1.0',END)
        btext = self.textMap[self.bodyText].regen(forDisplay=True)
        self.bodyText.insert(END,btext)
        self.colorize(self.bodyText,btext)
        self.bodyText.yview("moveto", oldScroll)
    def colorize(self,textWidget,progText):
        def colorizeSub(color,wordList):
            textWidget.tag_remove(color,'1.0',END)
            textWidget.tag_configure(color,foreground=color)
            keywords = re.compile(r'\b(' + string.join(wordList,"|") + r')\b')
            iter = keywords.finditer(progText)
            for match in iter:
                start, stop = match.span()
                textWidget.tag_add(color,"1.0+%dc" % start, "1.0+%dc" % stop)
        textWidget.tag_remove('hilite','1.0',END)
        colorizeSub(Colors.keyword, Lexis.keywords)
        colorizeSub(Colors.reserved, Lexis.reservedWords)
    def refresh(self):
        self.setSource()
    def goDiagram(self):
        self.central.showDiagram(self.name)
    def showSource(self,node):
        self.makeTop()
        topNode = node.getTopNode()
        self.text = self.nodeMap[topNode]
        self.text.tag_remove('hilite','1.0',END)
        start, end =  node.lineRange()
        startIdx = '%d.0' % int(start)
        endIdx = '%d.0' % (int(end)+1)
        self.text.tag_configure('hilite',background=Colors.locatecolor,foreground='black')
        self.text.see(startIdx)
        self.text.tag_add('hilite',startIdx,endIdx)

    def coolSource(self):
        self.text.tag_configure('hilite',background='white',foreground=Colors.locatecooledcolor)
    def makeTop(self):
        TkWorkaround.raiseWindow(self.toplevel)
    def rescueResource(self):
        return repr(self.toplevel.geometry())
    def setGeom(self,geom):
        self.toplevel.geometry(geom)

    def showError(self, unitType, lineNo):
        text = {'m': self.bodyText, 'i': self.specText}[unitType]
        startIdx = '%s.0' % int(lineNo)
        endIdx = '%s.0' % (int(lineNo)+1)
        text.tag_remove('hilite','1.0',END)
        text.tag_configure('hilite',background=Colors.locatecolor,foreground='black')
        text.see(startIdx)
        text.tag_add('hilite',startIdx,endIdx)
        self.makeTop()
Ejemplo n.º 8
0
class TextBox:
    def __init__(self):

        self.WIDTH = 600
        self.HEIGHT = 800
        self.FONT = "helvetica"
        self.FONT_SIZE = 12

        # colours specified as RGB fractions
        self.bg_input = [1, 1, 1]
        self.fg_input = [0, 0, 0]

        self.bg_article = [0, 0, 0]
        self.fg_min_article = [0.5, 0.5, 0.5]
        self.fg_max_article = [0.9, 0.9, 0.9]
        self.fg_solution_article = [1, 1, 1]  #[0.3, 0.5, 1.0] #[1, 0.7, 0.4]

        invert = False
        if invert:
            self.bg_input = [1. - v for v in self.bg_input]
            self.fg_input = [1. - v for v in self.fg_input]

            self.bg_article = [1. - v for v in self.bg_article]
            self.fg_min_article = [1. - v for v in self.fg_min_article]
            self.fg_max_article = [1. - v for v in self.fg_max_article]

        self.text = ""  # what is shown in the box
        self.allText = ""  # the text for the entire article
        self.sentences = []  # list of sentences in article
        # dictionary mapping from size to k-hot encoding indicating
        # which sentences are in the summary
        self.solutions = []
        # (not used) how much weight is put on each sentence
        self.weights = []

        self.only_summary = True
        self.summary_size = 1
        self.summary_coherence = 0.0
        self.summary_independence = 0.8

        self.summarizer = Summarizer(parent=self)

        self.root = Tk()

        self.draw(init=True)

        #self.root.mainloop()

    def draw(self, init=False):

        if init:
            # show main article body
            self.tk_article = ScrolledText(self.root)

            # let user paste and enter text
            self.tk_user_input = ScrolledText(self.root)

            self.tk_summary_size_scale = Scale(self.root)
            self.tk_summary_size_scale_label = Label(self.root, text="Length")

            self.tk_summary_coherence_scale = Scale(self.root)
            self.tk_summary_coherence_scale_label = Label(self.root,
                                                          text="Coherence")

            self.tk_summary_independence_scale = Scale(self.root)
            self.tk_summary_independence_scale_label = Label(
                self.root, text="Independence")

            self.tk_toggle_view = Button(self.root,
                                         text="more",
                                         command=self.handleToggleView)
            self.tk_recalculate = Button(self.root,
                                         text="Update",
                                         command=self.handleRecalculate)

            self.root.geometry("%dx%d" % (self.WIDTH, self.HEIGHT))
            self.root.title("QuickReader V4")

            self.tk_article.configure(width=25,
                                      height=6,
                                      bd=0,
                                      highlightthickness=0,
                                      wrap="word",
                                      font=self.FONT)

            self.tk_user_input.configure(width=25,
                                         height=3,
                                         bd=0,
                                         highlightthickness=0,
                                         wrap="word",
                                         font=self.FONT)

            self.tk_summary_size_scale.configure(
                bd=0,
                from_=0,
                to=20,
                orient=HORIZONTAL,
                sliderrelief=FLAT,
                command=lambda event: self.handleSlider(
                    self.tk_summary_size_scale.get()))

            ######
            self.tk_summary_coherence_scale.configure(
                bd=0,
                from_=0,
                to=1,
                orient=HORIZONTAL,
                sliderrelief=FLAT,
                resolution=0.05,
                command=lambda event: self.handleCoherenceSlider(
                    self.tk_summary_coherence_scale.get()))

            self.tk_summary_coherence_scale.set(self.summary_coherence)

            ######
            self.tk_summary_independence_scale.configure(
                bd=0,
                from_=0,
                to=1.5,
                orient=HORIZONTAL,
                sliderrelief=FLAT,
                resolution=0.05,
                command=lambda event: self.handleIndependenceSlider(
                    self.tk_summary_independence_scale.get()))

            self.tk_summary_independence_scale.set(self.summary_independence)

            # set colours
            self.root.configure(background="black")

            self.tk_summary_size_scale.configure(troughcolor="#444444",
                                                 fg="black",
                                                 background="white",
                                                 activebackground="#bbbbbb")

            self.tk_summary_coherence_scale.configure(
                troughcolor="#444444",
                fg="black",
                background="white",
                activebackground="#bbbbbb")

            self.tk_summary_independence_scale.configure(
                troughcolor="#444444",
                fg="black",
                background="white",
                activebackground="#bbbbbb")

            self.tk_article.configure(bg=toHex(self.bg_article),
                                      fg="white",
                                      insertbackground="blue")
            self.tk_article.vbar.configure(bg="white",
                                           width=10,
                                           troughcolor="black")

            self.tk_user_input.configure(bg=toHex(self.bg_input),
                                         fg=toHex(self.fg_input),
                                         insertbackground="blue")
            self.tk_user_input.vbar.configure(bg="white",
                                              width=10,
                                              troughcolor="black")

            self.tk_user_input.focus()
            self.tk_user_input.bind("<KeyRelease-Return>",
                                    (lambda event: self.handleUserInput(
                                        self.tk_user_input.get("0.0", END))))
            self.root.bind("<Configure>", self.resize)

    def setText(self, text, redraw=False):
        self.text = text
        if redraw: self.updateArticleInfo()

    def setSentences(self, sentences, redraw=False):
        self.sentences = sentences
        if redraw: self.updateArticleInfo()

    def setSolutions(self, solutions, redraw=False):
        self.solutions = solutions
        if redraw: self.updateArticleInfo()

    def setWeights(self, weights, redraw=False):
        self.weights = weights
        if redraw: self.updateArticleInfo()

    def handleToggleView(self):

        print("View toggle!")

        self.only_summary = not self.only_summary

        if self.only_summary:
            self.tk_toggle_view.configure(text="more")
        else:
            self.tk_toggle_view.configure(text="less")

        self.updateSummary()

    def handleRecalculate(self):
        print("Update!")

        self.handleUserInput(self.allText)

    def handleSlider(self, value):

        print("Slider:", value)

        self.summary_size = value

        self.updateSummary()

    def handleCoherenceSlider(self, value):

        print("Coherence Slider:", value)

        self.summary_coherence = value

        #self.updateSummary()

    def handleIndependenceSlider(self, value):

        print("Independence Slider:", value)

        self.summary_independence = value

        #self.updateSummary()

    def updateSummary(self):

        l = self.summary_size

        if self.only_summary and l != 0:
            self.setText('\n\n'.join([
                self.sentences[i] for i in range(len(self.sentences))
                if self.solutions[l][i] == 1
            ]))
        else:
            self.setText(self.allText, redraw=False)

        self.updateArticleInfo()

        self.setWeights([0. for _ in self.sentences], redraw=True)

        self.tk_article.yview_moveto(0)  #vbar.set(0, 0) #configure(jump=0)

    def handleUserInput(self, inStr):
        self.tk_user_input.delete("0.0", END)

        if inStr.strip() == "": return

        text = inStr

        text = ''.join([ch for ch in text if ord(ch) < 128])

        self.setText(text, redraw=False)
        self.setSolutions([], redraw=False)
        self.setWeights([], redraw=True)

        text, sentences, solutions = self.summarizer.summarize(
            text,
            coherence_weight=self.summary_coherence,
            independence_weight=self.summary_independence,
            size_weight=1.,
            beam_width=3,
            hard_size_limit=None)

        self.allText = text
        self.sentences = sentences
        self.solutions = solutions

        self.solutions[0] = [1. for _ in sentences]

        # get max length for summary
        max_len = max(solutions.keys())
        set_len = min(max_len, 3)
        self.tk_summary_size_scale.configure(from_=0, to=max_len)
        self.tk_summary_size_scale.set(set_len)
        self.summary_size = set_len

        # text: all the text in one long string
        # sentences: the text split up into a list of sentences
        # solution: dictionary mapping summary size to a one-hot vector over the sentences, indicating
        #   which sentences are included in the summarization

        # the text should be the same, but update it anyways since it needs to contain the
        #  exact same stuff as the sentences

        self.updateSummary()

        #self.updateArticleInfo()

    def resize(self, event=[]):
        LINEH = 20.0

        pixelX = self.root.winfo_width()
        pixelY = self.root.winfo_height()

        bf = 5  # buffer size in pixels

        # update find_icon, wiki_icon, and graph_icon

        # set toggle and recalculate button
        toggleW = 50
        toggleH = 35 * 1
        self.tk_toggle_view.place(x=pixelX - toggleW,
                                  y=0,
                                  width=toggleW,
                                  height=toggleH)

        updateW = 50
        updateH = 35 * 2
        self.tk_recalculate.place(x=pixelX - updateW,
                                  y=toggleH,
                                  width=updateW,
                                  height=updateH)

        buttonH = toggleH + updateH

        labelW = 90

        # set position of size scale
        scaleW = pixelX - updateW - labelW
        scaleH = 35
        self.tk_summary_size_scale.place(x=labelW,
                                         y=0,
                                         width=scaleW,
                                         height=scaleH)

        self.tk_summary_size_scale_label.place(x=0,
                                               y=0,
                                               width=labelW,
                                               height=scaleH)

        # set position of coherence scale
        coherenceW = pixelX - updateW - labelW
        coherenceH = 35
        self.tk_summary_coherence_scale.place(x=labelW,
                                              y=scaleH,
                                              width=scaleW,
                                              height=scaleH)

        self.tk_summary_coherence_scale_label.place(x=0,
                                                    y=scaleH,
                                                    width=labelW,
                                                    height=coherenceH)

        # set position of independence scale
        independenceW = pixelX - updateW - labelW
        independenceH = 35
        self.tk_summary_independence_scale.place(x=labelW,
                                                 y=scaleH + coherenceH,
                                                 width=scaleW,
                                                 height=scaleH)

        self.tk_summary_independence_scale_label.place(x=0,
                                                       y=scaleH + coherenceH,
                                                       width=labelW,
                                                       height=independenceH)

        # update user input
        inputW = pixelX
        inputH = int(3.0 * LINEH)
        self.tk_user_input.place(x=0,
                                 y=pixelY - inputH,
                                 width=inputW,
                                 height=inputH)

        # update article
        articleW = pixelX
        articleH = pixelY - inputH - scaleH - coherenceH - independenceH
        self.tk_article.place(x=0,
                              y=scaleH + coherenceH + independenceH,
                              width=articleW,
                              height=articleH)

    def updateArticleInfo(self):

        self.articleClear()

        self.articleCat(self.text)

        if self.weights != []:
            self.articleColour()

        self.root.update()

    def articleClear(self):
        self.tk_article.delete("1.0", END)
        self.tk_article.update()

        self.root.update()

        return

    def articleCat(self, inStr):

        self.tk_article.insert(END, inStr)

        self.tk_article.yview(END)

    def articleColour(self):
        '''
		solution = self.solutions[self.summary_size]

		allText = self.text #self.tk_article.get('1.0', 'end-1c')

		# make sure weights are normalised
		maxW = max(self.weights)
		minW = min(self.weights)

		weights = self.weights
		if maxW != minW:
			weights = [(v-minW)/(maxW-minW) for v in self.weights]

		for i in range(len(self.sentences)):
			if self.only_summary and solution[i] != 1.: continue

			s = self.sentences[i]
			if len(s.strip()) == 0:

				continue

			tagNameA = ''.join([random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10)])
			L_Size = 12 # if solution[i] == 1 else 10
			
			L_Colour = blend(self.fg_min_article, self.fg_max_article, weights[i])
			L_Colour = self.fg_solution_article if solution[i] == 1 else L_Colour

			countVar = StringVar(self.root)
			pos = self.tk_article.search(s, "1.0", stopindex="end", count=countVar)

			self.tk_article.tag_add(tagNameA, pos, "{} + {}c".format(pos, countVar.get()))

			bolding = "normal" #"bold" if self.solution[i] == 1 else "normal" #
			font = (self.FONT, L_Size, bolding)
			self.tk_article.tag_config(tagNameA, foreground=toHex(L_Colour), font=font)#self.FONT+' %s'%(L_Size))

		
		self.root.update()
		'''

        solution = self.solutions[self.summary_size]

        allText = self.text  #self.tk_article.get('1.0', 'end-1c')

        #print("=========")
        for i in range(len(self.sentences)):
            if self.only_summary and solution[i] != 1.: continue

            s = self.sentences[i]
            #if len(s.strip()) == 0:
            #	continue

            #print("- ", s)

            tagNameA = ''.join([
                random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10)
            ])
            L_Size = self.FONT_SIZE  # if solution[i] == 1 else 10

            L_Colour = self.fg_solution_article if solution[
                i] == 1 else self.fg_min_article
            #print("\t", L_Colour)

            countVar = StringVar(self.root)
            pos = self.tk_article.search(s,
                                         "1.0",
                                         stopindex="end",
                                         count=countVar)

            self.tk_article.tag_add(tagNameA, pos,
                                    "{} + {}c".format(pos, countVar.get()))

            bolding = "normal"  #"bold" if self.solution[i] == 1 else "normal" #
            font = (self.FONT, L_Size, bolding)
            self.tk_article.tag_config(tagNameA,
                                       foreground=toHex(L_Colour),
                                       font=font)  #self.FONT+' %s'%(L_Size))

        self.root.update()
Ejemplo n.º 9
0
class BackupUI(Frame):

    def __init__(self, parent=None, **options):
        Frame.__init__(self, parent, padx=10, pady=10)

        self.dataQueue = queue.Queue()
        self.thread = None
        self.outputPath = StringVar()
        self.userVar = IntVar()
        self.photoVar = IntVar()
        self.photoVar.set(1)

        self.top = Frame(self)
        self.top.pack(side=TOP, expand=YES, fill=X)
        self.top.config(bd=2)
        self.createForm()
        self.createButtons()
        self.createText()

    def createButtons(self):

        frm = Frame(self.top)
        frm.pack(side=RIGHT, expand=YES, anchor=NE)
        self.btnStart = Button(frm, text='开始备份', command=self.start)
        self.btnStart.pack(side=TOP)
        self.btnStop = Button(frm, text='停止备份', command=self.stop)
        self.btnStop.pack(side=TOP)
        self.btnStop.config(state=DISABLED)

        frm = Frame(self.top)
        frm.pack(side=RIGHT, expand=YES, anchor=NE)
        self.userCheck = Checkbutton(frm, text='备份好友资料', variable=self.userVar)
        self.userCheck.config(command=self.callback)
        self.userCheck.pack(side=TOP)
        self.photoCheck = Checkbutton(
            frm, text='备份相册照片', variable=self.photoVar)
        self.photoCheck.config(command=self.callback)
        self.photoCheck.pack(side=TOP)

        frm = Frame(self, pady=5, padx=5)
        frm.pack(side=TOP, anchor=W)
        self.btnSelect = Button(frm, text='选择保存路径', command=self.selectPath)
        self.btnSelect.pack(side=LEFT)
        self.savePath = Entry(frm, width=45, textvariable=self.outputPath)
        self.savePath.pack(side=LEFT)
        self.savePath.insert(END, os.path.abspath(os.path.join('.', 'output')))

    def createForm(self):
        self.login = Frame(self.top)
        # self.login.config(padx=4, pady=4)
        self.login.pack(side=LEFT, anchor=W)
        fields = const.LOGIN_FIELDS

        self.inputs = []
        for i in range(len(fields)):
            lbl = Label(self.login, text=fields[i])
            lbl.grid(row=i, column=0)
            var = StringVar()
            self.inputs.append(var)
            ent = Entry(self.login, textvariable=var)
            ent.grid(row=i, column=1)
            self.login.rowconfigure(i, weight=1)
        self.login.columnconfigure(0, weight=1)
        self.login.columnconfigure(1, weight=1)

    def createText(self):
        winfont = ('simhei', 10, 'normal')
        font = ('Helvetica', 12, 'normal')

        self.content = Frame(self, pady=5)
        self.content.pack(side=LEFT, expand=YES, fill=BOTH)
        self.text = ScrolledText(self.content)
        self.text.pack(side=TOP, expand=YES, fill=BOTH)
        self.text.config(bg='light gray', fg='black')
        self.text.config(padx=10, pady=10, font=winfont if isWin32 else font)
        self.text.insert(END, const.USER_GUIDE)
        self.text.config(state=DISABLED)

    def selectPath(self):
        path = askdirectory(initialdir='.')
        if path:
            self.savePath.delete(0, END)
            self.savePath.insert(END, path)

    def callback(self):
        #print('callback', self.userVar.get(), self.photoVar.get())
        pass

    def write(self, message):
        if message and message.strip():
            # timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.dataQueue.put(timestamp+" - "+message+'\n')

    def updateText(self, message):
        self.text.config(state=NORMAL)
        self.text.insert(END, str(message))
        self.text.config(state=DISABLED)
        self.text.see(END)
        self.text.update()

    def updateUI(self):
        try:
            message = self.dataQueue.get(block=False)
            if message:
                self.updateText(message)
        except queue.Empty:
            pass
        running = self.thread and self.thread.is_alive()
        self.btnStart.config(state=DISABLED if running else NORMAL)
        self.btnStop.config(state=NORMAL if running else DISABLED)
        self.after(100, self.updateUI)

    def stop(self):
        if getattr(self, 'thread'):
            self.thread.stop()

    def start(self):
        keys = ['username', 'password', 'target']
        values = map(lambda x: x.get(), self.inputs)
        if not any(values):
            showerror(const.NO_INPUT_TITLE, const.NO_INPUT_MESSAGE)
            return
        options = dict(zip(keys, values))
        options['output'] = self.savePath.get()
        options['include_user'] = self.userVar.get()
        options['include_photo'] = self.photoVar.get()
        print('启动参数:', options)
        self.text.config(state=NORMAL)
        self.text.delete('0.0', END)
        self.text.config(state=DISABLED)
        self.updateUI()
        self.thread = BackupThread(self, self.dataQueue, **options)
        self.thread.start()