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j/z |z]ͨIͩZhly{guLMcXKVJI\\υ>W.@XSYkikJKlk21QC>rB7xeO@㕘++\M?IʶkG/1`:Ĵ$Vk:,@`G9vIȶ\ o-um@(c~,$eVhȼmS+֪{EiZBRyme9W􊗫6w- OHpv+1W/db^A(eU:U8K(ˁ qcL`2K+RW|O/47/U2 K)C6ӡ;R4|<[,F669)|NDa+WR@m.Wggr ̀ꊫ7zkŃ0PRI"O8|R(ţϠUNǎkrKY KH2&L퐔^Kbx-0RvY B, n2=%j#us0G;"uwK+k;g?R~}F>~RPL-x(>>)}}7))hR%y`&GMcg>x]HN7X!w7wd.5>^  U<reXMH =nF#^/" >0XNx&@2i7>bHE<aU ?3ĉUzlW-f'r;xYTع,vTRE jd\%AWa]@%!#x8\EnAӏWȄqbAs; _ڡ[s3}r3|ga;R6/ None: # Defines self.frames_dict and self.data_frame based on a dir dir = Path(dir) if self.project_path not in dir.parents: raise ValueError( "'{0}' is not within the project path ('{1}').".format( dir, self.project_path ) ) try: self.frames_paths = sorted(Path(dir).glob("*.png")) # The commented out code causes an error with pytables. # It is currently unknown why. # init_nan = np.empty((len(self.images_paths), 2)).fill(np.nan) init_nan = np.empty((len(self.frames_paths), 2)) init_nan[:] = np.nan self.frames_names = [ str(Path(frame_path).relative_to(self.project_path)) for frame_path in self.frames_paths ] self.frames_dict = dict(zip(self.frames_names, self.frames_paths)) for bodypart in self.bodyparts: index = pd.MultiIndex.from_product( [[self.scorer], [bodypart], ["x", "y"]], names=["scorer", "bodyparts", "coords"], ) frame = pd.DataFrame(init_nan, columns=index, index=self.frames_names) self.data_frame = pd.concat([self.data_frame, frame], axis=1) except (TypeError, ValueError): pass def init_from_file(self, file: Union[str, Path]) -> None: # Defines self.frames_dict and self.data_frame based on a h5 file # Due to the inconsistencies between ``to_csv``, ``from_csv``, # ``read_csv``, etc., ONLY '.h5' files will be accepted. # https://github.com/pandas-dev/pandas/issues/13262 # TODO Proper extension checking file = Path(file) if file.is_file(): if file.suffix in (".hdf", ".h5"): try: self.data_frame = pd.read_hdf(file, "df_with_missing") except KeyError as e: raise KeyError( "The group 'df_with_missing' was not found in the .h5 file." ) from e elif file.suffix in (".pkl", ".pickle"): self.data_frame = pd.read_pickle(file) try: self.frames_names = sorted(self.data_frame.index.tolist()) except AttributeError as e: raise AttributeError( "Could not find the DataFrame index from the file ('{0}').".format( file ) ) from e self.frames_paths = [Path(self.project_path, _) for _ in self.frames_names] # TODO avoid copy pasted code self.frames_dict = dict(zip(self.frames_names, self.frames_paths)) def color_palette(self, number: int) -> Tuple[List, List, List]: # Create a list of QColors and their opposites equal in length to the # number of bodyparts # TODO set alpha from config hues = np.linspace(0, 1, number, endpoint=False) colors = [(h, 1, 1, 0.5) for h in hues] colors_opposite = [(abs(0.5 - h), 1, 1, 0.5) for h in hues] colors_opaque = [(h, 1, 1, 1) for h in hues] return colors, colors_opposite, colors_opaque def add_coords_to_dataframe(self, frame, bodypart, coords): if all(coord is None for coord in coords): coords = (np.nan, np.nan) try: self.data_frame.loc[frame, self.scorer][bodypart, "x"] = coords[0] self.data_frame.loc[frame, self.scorer][bodypart, "y"] = coords[1] except KeyError as e: raise KeyError( "The scorer of the config.yaml does not match this .h5 file." ) from e def get_coords_from_dataframe(self, frame, bodypart): x = self.data_frame.loc[frame, self.scorer][bodypart, "x"] y = self.data_frame.loc[frame, self.scorer][bodypart, "y"] if np.isnan(x): x = None if np.isnan(y): y = None return (x, y) def save_as_pkl(self, path): if path: pd.to_pickle(self.data_frame, path) def save_as_hdf(self, path): if path: self.data_frame.to_hdf(path, "df_with_missing", format="table", mode="w") PK!HHdlc_gui/gui.py""" This module handles all the GUI aspects of dlc_gui. This module creates a main window containing the main widget containing subset widgets. """ import sys from typing import Union import webbrowser from PySide2.QtCore import QEvent, QRectF, Qt from PySide2.QtGui import QBrush, QColor, QKeySequence, QPen, QPixmap from PySide2.QtWidgets import ( QAction, QApplication, QDesktopWidget, QFileDialog, QGraphicsEllipseItem, QGraphicsScene, QGraphicsView, QGridLayout, QLabel, QListWidget, QMainWindow, QShortcut, QSlider, QSplitter, QVBoxLayout, QWidget, ) import dlc_gui.data import dlc_gui.util class GraphicsScene(QGraphicsScene): def __init__(self, parent): super(GraphicsScene, self).__init__(parent) def load_image(self, image: str) -> None: # Load frame png into scene self.frame_image = QPixmap() self.frame_image.load(image) self.addPixmap(self.frame_image) class GraphicsView(QGraphicsView): def __init__(self, parent): super(GraphicsView, self).__init__(parent) self.scene = GraphicsScene(self) self.setScene(self.scene) self.fitInView(self.scene.sceneRect(), aspectRadioMode=Qt.KeepAspectRatio) self.viewport().setCursor(Qt.CrossCursor) # keep track of the current scale value to prevent zooming too far out self.current_scale = 1.0 def zoom(self, pos: tuple, scale: float, anchor: str = "NoAnchor") -> None: if anchor == "NoAnchor": self.setTransformationAnchor(QGraphicsView.NoAnchor) self.setResizeAnchor(QGraphicsView.NoAnchor) old_pos = self.mapToScene(*pos) # Prevent zooming out beyond 0.3 or in beyond 3.33 if (self.current_scale > 0.3 or scale > 1) and ( self.current_scale < 3.33 or scale < 1 ): self.scale(scale, scale) self.current_scale *= scale new_pos = self.mapToScene(*pos) translate_delta = (new_pos - old_pos).toTuple() self.translate(*translate_delta) # Scroll wheel to zoom in and out def wheelEvent(self, event): scale_factor = 1.25 if event.delta() > 0: self.zoom(event.pos().toTuple(), scale_factor) else: self.zoom(event.pos().toTuple(), 1 / scale_factor) # Toggle on dragging when middle mouse is pressed def mousePressEvent(self, event): if event.button() == Qt.MiddleButton: self.__og_pos = event.pos() self.setDragMode(QGraphicsView.ScrollHandDrag) else: return super(GraphicsView, self).mousePressEvent(event) # TODO find a legit way to engage the ScrollHandDrag mode # rather than simply using it to change the cursor look # Translate scene using scrollbars while middle button is held def mouseMoveEvent(self, event): if event.buttons() == Qt.MiddleButton: offset = self.__og_pos - event.pos() self.__og_pos = event.pos() self.verticalScrollBar().setValue( self.verticalScrollBar().value() + offset.y() ) self.horizontalScrollBar().setValue( self.horizontalScrollBar().value() + offset.x() ) else: super(GraphicsView, self).mouseMoveEvent(event) # Toggle off dragging when middle mouse is pressed def mouseReleaseEvent(self, event): if event.button() == Qt.MiddleButton: self.setDragMode(QGraphicsView.NoDrag) else: return super(GraphicsView, self).mouseReleaseEvent(event) class MainWidget(QWidget): """ Create the main user interface and controls, connected to DataModel """ def __init__(self, parent, config_path): super(MainWidget, self).__init__(parent) # Create the main widgets self.graphics_view = GraphicsView(self) self.bodyparts_view = QListWidget() self.dot_size_slider = QSlider(Qt.Horizontal) self.dot_size_label = QLabel(parent=self.dot_size_slider) self.frames_view = QListWidget() # Setup the data_model, get config values, and setup widgets based on data_model self.config_path = config_path data_model = dlc_gui.data.DataModel(self.config_path) self.init_from_data_model(data_model) # Set up the dot_size_slider dot_size_from_config = self.data_model.config_dict["dotsize"] self.dot_size_slider.setMinimum(1) self.dot_size_slider.setMaximum(100) self.dot_size_slider.setValue(dot_size_from_config) self.dot_size_slider.setTickPosition(QSlider.TicksBothSides) self.dot_size_slider.setTickInterval(10) self.dot_size_label.setText( "Label dot size: {} (from config.yaml)".format(dot_size_from_config) ) self.dot_size_slider.sliderReleased.connect( lambda: self.dot_size_label.setText( "Label dot size: {}".format(self.dot_size_slider.value()) ) ) self.dot_size_slider.sliderReleased.connect(lambda: self.update_scene()) # Add a widget to add a layout containing the bodyparts and the slider labeling_widget = QWidget() labeling_layout = QVBoxLayout() labeling_layout.addWidget(self.bodyparts_view) labeling_layout.addWidget(self.dot_size_label) labeling_layout.addWidget(self.dot_size_slider) labeling_widget.setLayout(labeling_layout) # Set the main layout of Widget main_layout = QGridLayout() splitter = QSplitter() splitter.addWidget(self.frames_view) splitter.addWidget(self.graphics_view) splitter.addWidget(labeling_widget) splitter.setStretchFactor(1, 1) main_layout.addWidget(splitter) self.setLayout(main_layout) # Set up events self.frames_view.currentItemChanged.connect(lambda x: self.update_scene()) self.graphics_view.scene.installEventFilter(self) shortcut_next_bodypart = QShortcut(QKeySequence("d"), self) shortcut_prev_bodypart = QShortcut(QKeySequence("a"), self) shortcut_next_frame = QShortcut(QKeySequence("s"), self) shortcut_prev_frame = QShortcut(QKeySequence("w"), self) # setattr is used as an assignment function, because lambdas cannot assign # prior to python 3.8 shortcut_next_bodypart.activated.connect( lambda: setattr(self, "current_bodypart_row", self.current_bodypart_row + 1) ) shortcut_prev_bodypart.activated.connect( lambda: setattr(self, "current_bodypart_row", self.current_bodypart_row - 1) ) shortcut_next_frame.activated.connect( lambda: setattr(self, "current_frame_row", self.current_frame_row + 1) ) shortcut_prev_frame.activated.connect( lambda: setattr(self, "current_frame_row", self.current_frame_row - 1) ) self.save_file_dialog = QFileDialog() self.save_file_dialog.setFileMode(QFileDialog.AnyFile) self.save_file_dialog.setAcceptMode(QFileDialog.AcceptSave) def init_from_data_model_from_file(self, dataframe_file) -> None: data_model = dlc_gui.data.DataModel(self.config_path) try: data_model.init_from_file(dataframe_file) except (KeyError, AttributeError) as e: self.send_status( "Error: {} is not structured correctly.".format(dataframe_file), 5 ) raise e except Exception: pass self.init_from_data_model(data_model) def init_from_data_model_from_dir(self, dir: str) -> None: data_model = dlc_gui.data.DataModel(self.config_path) try: data_model.init_from_dir(dir) except Exception: pass if not data_model.frames_dict and dir is not None: self.send_status("Error: No frames (*.png) found in {}".format(dir), 5) else: self.init_from_data_model(data_model) def init_from_data_model(self, data_model) -> None: self.data_model = data_model self.bodyparts = self.data_model.bodyparts self.project_path = self.data_model.project_path # Populate the frames and bodyparts lists if self.data_model.frames_dict: self.frames_dict = self.data_model.frames_dict self.frames_view.clear() for frame in self.frames_dict.keys(): self.frames_view.addItem(frame) self.bodyparts_view.clear() for bodypart in self.bodyparts: self.bodyparts_view.addItem(bodypart) # Convert tuples to QColors self.data_model.colors = [ QColor.fromHsvF(*color) for color in self.data_model.colors ] self.data_model.colors_opposite = [ QColor.fromHsvF(*color) for color in self.data_model.colors_opposite ] self.data_model.colors_opaque = [ QColor.fromHsvF(*color) for color in self.data_model.colors_opaque ] # Set initial selections for both listwidgets, load the first frame, # and add color icons frames_view_items = self.frames_view.findItems("*", Qt.MatchWildcard) if frames_view_items: self.frames_view.setCurrentItem(frames_view_items[0]) self.graphics_view.scene.load_image(str(list(self.frames_dict.values())[0])) self.bodyparts_view_items = self.bodyparts_view.findItems("*", Qt.MatchWildcard) if self.bodyparts_view_items: self.bodyparts_view.setCurrentItem(self.bodyparts_view_items[0]) for item, color in zip( self.bodyparts_view_items, self.data_model.colors_opaque ): pixmap = QPixmap(100, 100) pixmap.fill(color) item.setIcon(pixmap) self.update_scene() def eventFilter(self, obj, event): """ Implement left and right mouse clicking functionalities """ # Check if the click is within the QGraphicsView if ( obj is self.graphics_view.scene and event.type() == QEvent.Type.GraphicsSceneMousePress ): scene_pos = event.scenePos() coords = (scene_pos.x(), scene_pos.y()) frame = self.current_frame_text bodypart = self.current_bodypart_text if frame and bodypart: if event.buttons() == Qt.LeftButton: self.data_model.add_coords_to_dataframe(frame, bodypart, coords) elif event.buttons() == Qt.RightButton: self.data_model.add_coords_to_dataframe( frame, bodypart, (None, None) ) self.update_scene() return super(MainWidget, self).eventFilter(obj, event) @property def current_bodypart_row(self) -> int: return self.bodyparts_view.currentRow() @current_bodypart_row.setter def current_bodypart_row(self, row) -> None: self.bodyparts_view.setCurrentRow(row) @property def current_frame_row(self) -> int: return self.frames_view.currentRow() @current_frame_row.setter def current_frame_row(self, row) -> None: self.frames_view.setCurrentRow(row) @property def current_bodypart_text(self) -> Union[str, None]: try: return self.bodyparts_view.currentItem().text() except AttributeError: return None @property def current_frame_text(self) -> Union[str, None]: try: return self.frames_view.currentItem().text() except AttributeError: return None def send_status(self, msg, timeout) -> None: self.parent().status_bar.showMessage(msg, timeout * 1000) def save_as_pkl(self) -> None: self.save_file_dialog.selectFile(str(self.data_model.save_path_pkl)) self.save_file_dialog.setNameFilter("(*.pkl *.pickle)") self.save_file_dialog.setDefaultSuffix(".pkl") if self.save_file_dialog.exec(): save_path = self.save_file_dialog.selectedFiles()[0] self.data_model.save_as_pkl(save_path) def save_as_hdf(self) -> None: self.save_file_dialog.selectFile(str(self.data_model.save_path_hdf)) self.save_file_dialog.setNameFilter("(*.h5 *.hdf)") self.save_file_dialog.setDefaultSuffix(".h5") if self.save_file_dialog.exec(): save_path = self.save_file_dialog.selectedFiles()[0] self.data_model.save_as_hdf(save_path) # Updating scene is in MainWidget and not GraphicsScene because it needs to know # current frame and current bodypart, both properties of MainWidget def update_scene(self) -> None: def add_dots_to_scene( coords: tuple, size: float, brush_color: QColor, pen_color: QColor, tooltip: str, ): # Adds dots to the scene x, y = coords dot_rect = QRectF(x - size / 2, y - size / 2, size, size) dot_brush = QBrush(Qt.SolidPattern) dot_brush.setColor(brush_color) dot_pen = QPen(dot_brush, size / 40) dot_pen.setColor(pen_color) dot_ellipse = QGraphicsEllipseItem(dot_rect) dot_ellipse.setPen(dot_pen) dot_ellipse.setBrush(dot_brush) dot_ellipse.setToolTip(tooltip) self.graphics_view.scene.addItem(dot_ellipse) self.graphics_view.scene.clear() frame = self.current_frame_text if frame: self.graphics_view.scene.load_image(str(self.frames_dict[frame])) dot_size = self.dot_size_slider.value() if self.data_model.data_frame is not None: for bodypart, brush_color, pen_color in zip( self.bodyparts, self.data_model.colors, self.data_model.colors_opposite, ): coords = self.data_model.get_coords_from_dataframe(frame, bodypart) if all(coord is not None for coord in coords): add_dots_to_scene( coords, dot_size, brush_color, pen_color, bodypart ) class MainWindow(QMainWindow): """ Define the main window and its menubar and statusbar """ def __init__(self, config=None, relative_size=0.8): super(MainWindow, self).__init__() self.setWindowTitle("DeepLabCut Labeling GUI") # Statusbar # must be defined before children for children to access it self.status_bar = self.statusBar() self.open_file_dialog = QFileDialog() if config is None: config = self.open_file("(*.yml *.yaml)", "config.yaml") if config == "" or config is None: print("No config.yaml file provided, exiting...") sys.exit() self.main_widget = MainWidget(self, config) self.open_file_dialog.setDirectory( str(self.main_widget.data_model.labeled_data_path) ) # Menubar self.open_frames_dir = QAction("Open directory of frames", self) self.open_frames_dir.setShortcut(QKeySequence("Ctrl+O")) self.open_frames_dir.triggered.connect( lambda x: self.main_widget.init_from_data_model_from_dir(self.open_dir()) ) self.open_dataframe_file = QAction("Open *.h5 or *.pkl file", self) self.open_dataframe_file.setShortcut(QKeySequence("Ctrl+F")) self.open_dataframe_file.triggered.connect( lambda x: self.main_widget.init_from_data_model_from_file( self.open_file( "(*.h5 *.hdf *.pkl *.pickle)", str(self.main_widget.data_model.save_path_hdf), ) ) ) save_as_hdf = QAction("Save as .h5", self) save_as_hdf.setShortcut(QKeySequence("Ctrl+S")) save_as_hdf.triggered.connect(lambda x: self.main_widget.save_as_hdf()) save_as_pkl = QAction("Save as .pkl", self) save_as_pkl.triggered.connect(lambda x: self.main_widget.save_as_pkl()) help_url = "https://dlc-gui.readthedocs.io/en/latest/README.html#using-the-gui" open_help = QAction("Help", self) open_help.setShortcut(QKeySequence("Ctrl+H")) open_help.triggered.connect(lambda x: webbrowser.open(help_url)) self.menu_bar = self.menuBar() self.file_menu = self.menu_bar.addMenu("File") self.file_menu.addAction(self.open_frames_dir) self.file_menu.addAction(self.open_dataframe_file) self.file_menu.addAction(save_as_hdf) self.file_menu.addAction(save_as_pkl) self.help_menu = self.menu_bar.addMenu("Help") self.help_menu.addAction(open_help) # Window dimensions self.resize(QDesktopWidget().availableGeometry(self).size() * relative_size) self.setCentralWidget(self.main_widget) # ## TODO fix bug of open_file_dialog object remembering ## selectedFiles and starting directory # def open_file(self, name_filter: str, select_file: str = None) -> Union[str, None]: if select_file is not None: self.open_file_dialog.selectFile(select_file) self.open_file_dialog.setFileMode(QFileDialog.ExistingFile) self.open_file_dialog.setNameFilter(name_filter) if self.open_file_dialog.exec(): file = self.open_file_dialog.selectedFiles()[0] return file return None def open_dir(self) -> Union[str, None]: self.open_file_dialog.setFileMode(QFileDialog.Directory) if self.open_file_dialog.exec(): dir = self.open_file_dialog.selectedFiles()[0] return dir return None def show(config: Union[None, str] = None, relative_size: float = 0.8) -> None: """ Show the GUI. Parameters ---------- config : str or None, optional (default None) The config.yaml file to use. May be None to use the GUI to pick the config.yaml file. relative_size : float, optional (default 0.8) What portion of the display to set the main window's size to. """ app = QApplication(sys.argv) window = MainWindow(config, relative_size) window.show() sys.exit(app.exec_()) PK!䍇dlc_gui/util.py# TODO use modern API import ruamel.yaml def read_config_file(config_path): """ Read a config.yaml file and return as a dictionary. """ with open(config_path, "r") as f: config_dict = ruamel.yaml.load(f.read(), Loader=ruamel.yaml.Loader) return config_dict def write_config_file(write_path, config_dict): """ Write yaml dictionary to `write_path`. """ with open(write_path, "w") as f: f.write(ruamel.yaml.dump(config_dict, default_flow_style=False)) PK!pdlc_gui-0.3.0.dist-info/LICENSE GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. PK!HڽTUdlc_gui-0.3.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HRX| dlc_gui-0.3.0.dist-info/METADATAMo0 9Q?(*@C uh]AClɴ] /Ĵ ';vl7UL;Is̹<Rj!@v1IaU%Iv+r%Y"6&ЭT t(.{+eiI]4pqq]X^8mE Ҽ+~i&Qf4ddZpPK/d]y='َJ`8=g =;1od]J.BUj>Oe^x%SMnYM}MGzO= '57TUb F36|N;Le žI2{oPK!HZ{dlc_gui-0.3.0.dist-info/RECORDuAc@} ,2bADdSGPM !A~dΙdx{RȜ-#FIZ '}2ycyZ$KҰ]MtE$v 94]cW/pgEQ6 !D(b酕eX5>-Um{4{@`l-U$GdAwיRdc(. Q*1Kx]"a7U׭_9[5ee~9{cf