예제 #1
0
파일: view.py 프로젝트: berkobob/myPicasa
    def __init__(self, controller):
        self.controller = controller  # function to call

        self.root = Tk()  # create main window called root
        self.root.state('zoomed')  # have root be full screen
        self.root.title('Picasa')  # name the display
        self.root.protocol(
            'WM_DELETE_WINDOW',
            lambda: self.controller('stop'))  # Trap close window

        self.menu = PicasaMenu(self.root, controller)  # create main menu
        self.root.config(menu=self.menu)  # add menu to window

        self.TAB = PanedWindow(self.root, orient=VERTICAL)  # Top And Bottom
        self.TAB.grid(sticky='nsew')
        self.LAR = PanedWindow(self.root, orient=HORIZONTAL)  # Left And Right
        self.LAR.grid(sticky='nsew')
        self.TAB.add(self.LAR)

        self.tree = Tree(self.root, controller)  # create tree
        self.LAR.add(self.tree)

        self.gallery = Gallery(self.root, controller)  # create all pics
        self.LAR.add(self.gallery)

        self.status = Status(self.TAB, controller)  # create status text
        self.TAB.add(self.status)

        self.TAB.config(sashrelief='raised')  # make sash visible
        self.LAR.config(sashrelief='raised')

        self.root.grid_columnconfigure(0, weight=1)  # make all resizeable
        self.root.grid_rowconfigure(0, weight=1)

        self.TAB.sash_place(0, 1, 1000)
예제 #2
0
def show_gallery(path):
    global g
    user = g.user
    if user is None and not cfg()["public_access"]:
        return render("gallery.html", authn_error="only logged in users may view this page")
    path = path.encode("utf-8")
    check_jailed_path(path, "data")
    groups = get_access_groups(path)
    if not cfg()["public_access"]:
        if not is_admin_mode(user) and not access_permitted(groups, user["groups"]):
            return render("gallery.html", authn_error=True)

    gallery = Gallery(path, follow_freedesktop_standard = cfg()["follow_freedesktop_standard"])
    gallery.populate()
    if cfg()["public_access"] or is_admin_mode(user):
        galleries = gallery.get_galleries()
    else:
        galleries = [gal for gal in gallery.get_galleries() if access_permitted(get_access_groups(gal["key"]), user["groups"])]
    groups_error = None
    if request.method == 'POST':
        action = request.form["action"]
        if action == "save":
            if not is_admin_mode(user):
                return render("gallery.html", authn_error=True)
            groups = request.form["groups_string"].split()
            try:
                set_access_groups(path, groups)
            except IOError, ioe:
                groups_error = "%s" %ioe
        else:
            raise Exception("Unknown gallery editing action: \"%s\"" %action)
예제 #3
0
def write_dicom_volume_html_flip(volume, path, title):
    gal = Gallery('pethtmlview/' + path, score=False, title=title)
    for i in range(volume.shape[0]):
        transposedImage = cv2.transpose(volume[i])
        flippedImage = cv2.flip(transposedImage, 1)
        cv2.imwrite(gal.next(), flippedImage)
        pass
    gal.flush()
예제 #4
0
def main(_):
    X = tf.placeholder(tf.float32, shape=(None, None, None, 3), name="images")
    is_training = tf.placeholder(tf.bool, name="is_training")
    anchor_th = tf.constant(FLAGS.anchor_th, tf.float32)
    nms_max = tf.constant(FLAGS.nms_max, tf.int32)
    nms_th = tf.constant(FLAGS.nms_th, tf.float32)
    model = Model(X, anchor_th, nms_max, nms_th, is_training, FLAGS.model,
                  'xxx')
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    with tf.Session(config=config) as sess:
        model.loader(sess)
        if FLAGS.input:
            assert os.path.exists(FLAGS.input)
            image = cv2.imread(FLAGS.input, cv2.IMREAD_COLOR)
            batch = np.expand_dims(image, axis=0).astype(dtype=np.float32)
            boxes, probs = sess.run([model.boxes, model.probs],
                                    feed_dict={
                                        X: batch,
                                        is_training: False
                                    })
            save_prediction_image(FLAGS.input + '.prob.png', image, boxes,
                                  probs)
        if FLAGS.input_db:
            assert os.path.exists(FLAGS.input_db)
            import picpac
            from gallery import Gallery
            picpac_config = {
                "db": FLAGS.input_db,
                "loop": False,
                "shuffle": False,
                "reshuffle": False,
                "annotate": False,
                "channels": 3,
                "stratify": False,
                "dtype": "float32",
                "batch": 1,
                "transforms": []
            }
            stream = picpac.ImageStream(picpac_config)
            gal = Gallery(FLAGS.input_db + '.out')
            C = 0
            for _, images in stream:
                boxes, probs = sess.run([model.boxes, model.probs],
                                        feed_dict={
                                            X: images,
                                            is_training: False
                                        })
                save_prediction_image(gal.next(), images[0], boxes, probs)
                C += 1
                if FLAGS.max and C >= FLAGS.max:
                    break
                pass
            pass
            gal.flush()
    pass
예제 #5
0
def main(_):
    assert FLAGS.out
    assert FLAGS.db and os.path.exists(FLAGS.db)

    picpac_config = dict(
        seed=2016,
        #loop=True,
        shuffle=True,
        reshuffle=True,
        #resize_width=256,
        #resize_height=256,
        round_div=FLAGS.stride,
        batch=1,
        split=1,
        split_fold=0,
        annotate='json',
        channels=FLAGS.channels,
        stratify=True,
        pert_color1=20,
        pert_angle=20,
        pert_min_scale=0.8,
        pert_max_scale=1.2,
        #pad=False,
        pert_hflip=True,
        pert_vflip=True,
        channel_first=False  # this is tensorflow specific
        # Caffe's dimension order is different.
    )

    stream = picpac.ImageStream(FLAGS.db,
                                perturb=False,
                                loop=False,
                                **picpac_config)

    gal = Gallery(FLAGS.out)
    cc = 0
    with Model(FLAGS.model, name=FLAGS.name, prob=True) as model:
        for images, _, _ in stream:
            #images *= 600.0/1500
            #images -= 800
            #images *= 3000 /(2000-800)
            _, H, W, _ = images.shape
            if FLAGS.max_size:
                if max(H, W) > FLAGS.max_size:
                    continue
            if FLAGS.patch:
                stch = Stitcher(images, FLAGS.patch)
                probs = stch.stitch(model.apply(stch.split()))
            else:
                probs = model.apply(images)
            cc += 1
            save(gal.next(), images, probs)
            if FLAGS.max and cc >= FLAGS.max:
                break
    gal.flush()
    pass
예제 #6
0
def write_dicom_volume_html_resize_twice(volume, path, title):
    gal = Gallery('pethtmlview/' + path, score=False, title=title)
    for i in range(volume.shape[0]):
        resizedImage = cv2.resize(volume[i], (0, 0),
                                  fx=2.0,
                                  fy=2.0,
                                  interpolation=cv2.INTER_NEAREST)
        cv2.imwrite(gal.next(), resizedImage)
        pass
    gal.flush()
예제 #7
0
def write_dicom_volume_html_flip_resize(volume, path, title):
    gal = Gallery('pethtmlview/' + path, score=False, title=title)
    for i in range(volume.shape[0]):
        transposedImage = cv2.transpose(volume[i])
        flippedImage = cv2.flip(transposedImage, 1)
        resizedImage = cv2.resize(flippedImage, (0, 0),
                                  fx=0.5,
                                  fy=0.5,
                                  interpolation=cv2.INTER_NEAREST)
        cv2.imwrite(gal.next(), resizedImage)
        pass
    gal.flush()
예제 #8
0
파일: fcn-cls-val.py 프로젝트: zzdaizz/cls
def main (_):
    assert FLAGS.out
    assert FLAGS.db and os.path.exists(FLAGS.db)

    picpac_config = dict(seed=2016,
                #loop=True,
                shuffle=True,
                reshuffle=True,
                max_size = 400,
                #resize_width=256,
                #resize_height=256,
                round_div = FLAGS.stride,
                batch=1,
                split=1,
                split_fold=0,
                annotate='json',
                channels=FLAGS.channels,
                stratify=True,
                #pad=False,
                channel_first=False # this is tensorflow specific
                                    # Caffe's dimension order is different.
                )

    stream = picpac.ImageStream(FLAGS.db, perturb=False, loop=False, **picpac_config)


    gal = Gallery(FLAGS.out, score=True)
    cc = 0
    with Model(FLAGS.model, prob=True) as model:
        for images, _, _ in stream:
            #images *= 600.0/1500
            #images -= 800
            #images *= 3000 /(2000-800)
            _, H, W, _ = images.shape
            if FLAGS.max_size:
                if max(H, W) > FLAGS.max_size:
                    continue
            print(images.shape)
            # fcn-cls do not have patch
            # if FLAGS.patch:
                
            #     stch = Stitcher(images, FLAGS.patch)
            #     probs = stch.stitch(model.apply(stch.split()))
            # else:
            #     probs = model.apply(images)
            probs, scores = model.apply(images)
            cc += 1
            save(gal.next(score=scores[0]), images, probs)
            if FLAGS.max and cc >= FLAGS.max:
                break
    gal.flush(rank=True)
    pass
예제 #9
0
def main (_):
    assert FLAGS.db and os.path.exists(FLAGS.db)
    assert FLAGS.model and os.path.exists(FLAGS.model + '.meta')

    L = tf.placeholder(tf.float32, shape=(None, None, None, 1))

    mg = meta_graph.read_meta_graph_file(FLAGS.model + '.meta')
    logits, = tf.import_graph_def(mg.graph_def, name='colorize',
                        #input_map={'L:0':L},
                        input_map={'fifo_queue_Dequeue:0':L},
                        return_elements=['logits:0'])
    prob = tf.nn.softmax(logits)
    saver = tf.train.Saver(saver_def=mg.saver_def, name='colorize')

    picpac_config = dict(seed=2016,
                cache=False,
                max_size=200,
                min_size=192,
                crop_width=192,
                crop_height=192,
                shuffle=True,
                reshuffle=True,
                batch=1,
                round_div=FLAGS.stride,
                channels=3,
                stratify=False,
                channel_first=False # this is tensorflow specific
                                    # Caffe's dimension order is different.
                )

    stream = picpac.ImageStream(FLAGS.db, perturb=False, loop=False, **picpac_config)

    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        saver.restore(sess, FLAGS.model)
        gallery = Gallery(FLAGS.output, cols=2, header=['groundtruth', 'prediction'])
        c = 0
        for images, _, _ in stream:
            if FLAGS.max and (c >= FLAGS.max):
                break
            l, ab, w = _pic2pic.encode_lab(images.copy(), FLAGS.downsize)
            ab_p, = sess.run([prob], feed_dict={L: l})
            y_p = decode_lab(l, ab_p, T=FLAGS.T)
            cv2.imwrite(gallery.next(), images[0])
            cv2.imwrite(gallery.next(), y_p[0])
            c += 1
            print('%d/%d' % (c, FLAGS.max))
            pass
        gallery.flush()
        pass
    pass
예제 #10
0
def recursive_populate(path, log_freq, follow_freedektop_standard):
    try:
        gallery = Gallery(path, log_freq, follow_freedektop_standard)
        gallery.populate()
        stats = gallery.stats.clone()
        for g in gallery.gallery_paths:
            subgallery, substats = recursive_populate(os.path.join(gallery.path, g), log_freq, follow_freedektop_standard)
            if substats is None:
                break
            else:
                stats.increase(substats)
    except KeyboardInterrupt:
        print "\n%sProcess interrupted by user!%s" %(Color.RED, Color.RESET)
        return None, None
    return gallery, stats
예제 #11
0
def main(_):
    X = tf.placeholder(tf.float32, shape=(None, None, None, 1), name="images")
    model = Model(X, FLAGS.model, 'xxx')
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    with tf.Session(config=config) as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        model.loader(sess)
        # 模型至此导入完毕
        # 注意如果要读入图片预测,需要进行下述预处理
        # 1. 转成灰度图, 比如用cv2.imread(..., cv2.IMREAD_GRAYSCALE)
        # 2. resize成固定大小,和train.sh中的参数匹配
        # 3. 比如灰度图是image, 那么对应的batch = image[np.newaxis, :, :, np.newaxis], 就可以送入tf.session预测了

        gal = Gallery('output', cols=2, ext='.jpg')
        CC = 0
        stream = picpac.ImageStream({
            'db':
            FLAGS.db,
            'loop':
            False,
            'channels':
            1,
            'threads':
            1,
            'shuffle':
            False,
            'transforms': [{
                "type": "resize",
                "width": FLAGS.width,
                "height": FLAGS.height
            }]
        })
        for meta, batch in stream:
            if CC > FLAGS.max:
                break
            print(meta.ids)
            image = batch[0]
            logits = sess.run(model.logits, feed_dict={X: batch})
            # 把logits转换成字符串
            label = logits2text(logits)
            '''END INFERENCE'''
            save_prediction_image(gal, image, label)
            CC += 1
        gal.flush()
    pass
예제 #12
0
def main(_):
    X = tf.placeholder(tf.float32,
                       shape=(None, None, None, FLAGS.channels),
                       name="images")
    model = Model(X, FLAGS.model, 'xxx')
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True

    mold = Scaling(stride=FLAGS.stride)
    with tf.Session(config=config) as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        model.loader(sess)

        gal = Gallery('output', ext='.png')
        CC = 0
        if FLAGS.list:
            with open(FLAGS.list, 'r') as f:
                for line in f:
                    if CC > FLAGS.max:
                        break
                    path, label = line.strip().split(',')
                    label = int(label)

                    print(path)
                    if FLAGS.channels == 3:
                        image = cv2.imread(path, cv2.IMREAD_COLOR)
                    elif FLAGS.channels == 1:
                        image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
                    else:
                        assert False

                    image = cv2.resize(image, (FLAGS.resize, FLAGS.resize))

                    probs, heatmap = sess.run(
                        [model.probs, model.heatmap],
                        feed_dict={X: mold.batch_image(image)})
                    probs = probs[0]
                    heatmap = mold.unbatch_prob(image, heatmap)
                    '''END INFERENCE'''

                    save_prediction_image(gal, image, label, probs, heatmap)
                    CC += 1
        gal.flush()
    pass
예제 #13
0
파일: predict.py 프로젝트: Lingrui/arch
def main(_):
    cc = 0
    with Model(FLAGS.model, name=FLAGS.name) as model:
        for out, inp in DS:
            gal = Gallery(out, ext='.gif')
            for root, dirs, files in os.walk(inp, topdown=False):
                for path in files:
                    image = cv2.imread(os.path.join(root, path),
                                       cv2.IMREAD_GRAYSCALE)
                    image = image.astype(np.float32)
                    image = cv2.resize(image, None, fx=FLAGS.rx, fy=FLAGS.rx)

                    prob = model.apply(
                        np.expand_dims(np.expand_dims(image, axis=0),
                                       axis=3))[0]
                    visualize(gal.next(), image, prob)
            gal.flush()
    pass
예제 #14
0
 def __init__(self,status_update_func,screen):
     config = Config('space_window.conf',__file__)    
     self._start_with=config.get('global','start_with','streams')
     self._current_stream=None
     self._resume_stream=None
     self._check_timer_delay=20
     self._check_timer=None
     self._wait=False
     self._streams=Streams.load()
     self._nasa=NasaPod(screen)
     self._gallery=Gallery(status_update_func,screen)
     self._music=Music(status_update_func)
     self._clock=Clock(screen)
     self._mopidy=None
     self._status_update=status_update_func    
     if not _standalone:
         threading.Thread(target=self.launch_mopidy).start()
     self._streams.set_status_func(status_update_func)
     self._resume_func=self.run_something
예제 #15
0
파일: sample.py 프로젝트: Lingrui/arch
def main(_):
    picpac_config = dict(
        seed=2016,
        shuffle=True,
        batch=1,
        annotate='json',
        channels=1,
        perturb=False,
        loop=False,
        stratify=True,
        channel_first=False  # this is tensorflow specific
        # Caffe's dimension order is different.
    )
    tr_stream = picpac.ImageStream(FLAGS.db, **picpac_config)
    gal = Gallery('sample', ext='.gif')
    cc = 0
    for image, label, _ in tr_stream:
        cc += 1
        visualize(gal.next(), image[0], label[0, :, :, 0])
        if cc >= FLAGS.classes - 1:
            break
        pass
    gal.flush()
예제 #16
0
    def build(self):
        manager = ScreenManager()

        manager.add_widget(Login(name='login'))
        manager.add_widget(Incorrect(name='incorrect'))
        manager.add_widget(Gallery(name='gallery'))

        manager.add_widget(Info(name='porsche'))
        manager.add_widget(Info(name='lotus'))
        manager.add_widget(Info(name='chevrolet'))
        manager.add_widget(Info(name='alfaromeo'))

        manager.add_widget(Stopwatch(name='stopwatch'))
        manager.add_widget(Calculator(name='calculator'))

        return manager
예제 #17
0
    def post(self):
        url_id = int(self.request.get('gallery_id'))
        gallery_details = Gallery.get_by_id(url_id)

        upload = self.get_uploads()[0]
        blobinfo = blobstore.BlobInfo(upload.key())
        filename = blobinfo.filename

        upload_image = Image()
        upload_image.image_name = filename
        upload_image.blobs = upload.key()
        upload_image.put()

        gallery_details.image_key.append(upload_image.key)
        gallery_details.put()

        self.redirect('/gallery?url=' + str(gallery_details.key.urlsafe()))
예제 #18
0
파일: download.py 프로젝트: causemx/Orb
 def __init__(self,
              session,
              gallery_url,
              force_origin=False,
              page_fetcher_num=1,
              page_loader_num=2,
              image_downloader_num=10,
              download_timeout=7.0):
     self.session = session
     self.download_timeout = download_timeout
     self.force_origin = force_origin
     self.page_fetcher_num = page_fetcher_num
     self.page_loader_num = page_loader_num
     self.image_downloader_num = image_downloader_num
     self.gallery = Gallery.from_url(gallery_url)
     self.planned_pages = asyncio.queues.Queue()
     self.unloaded_pages = asyncio.queues.Queue()
     self.loaded_pages = asyncio.queues.Queue()
예제 #19
0
파일: bot.py 프로젝트: qnnnnez/e-downloader
async def handle_all(message: types.Message):
    if is_group_chat(message.chat) and not get_group_enabled(message.chat):
        return

    all_urls = gallery_url_pattern.findall(message.text)
    all_urls = [groups[0] for groups in all_urls]
    if not all_urls:
        return

    loop = asyncio.get_event_loop()

    pending = []
    for url in all_urls:
        gallery = Gallery.from_url(url)
        task = asyncio.create_task(send_gallery_info(message, gallery))
        pending.append(task)

    while pending:
        done, pending = await asyncio.wait(pending)
예제 #20
0
 def on_btn_runGallery(self):
     title = self.pte_galleryTitle.toPlainText()
     list = []
     for i in range(self.tbl_gallery.rowCount()):
         new = []
         for j in range(4):
             if self.tbl_gallery.item(i, j) != None:
                 new.append(int(self.tbl_gallery.item(i, j).text()))
             else:
                 new.append('')
         list.append(new)
     print(list)
     gl = Gallery(title, list, self.time_ms, self.intensity,
                  self.currentFilePath, mm)
     gl.run_field()
     #gl.show_slides()
     gl.run()
예제 #21
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'

        # GET USER KEY
        user = users.get_current_user()
        myuser_key = ndb.Key('MyUser', user.user_id())
        user_info = MyUser.get_by_id(myuser_key.id())

        action = self.request.get('button')

        # CREATE New Gallery
        if action == 'Create New Gallery':
            # GET NEW GALLERY NAME
            gallery_name = self.request.get('gallery_name')

            # CREATE NEW GALLERY
            new_gallery = Gallery(creator=myuser_key, gallery_name=gallery_name)
            new_gallery.put()

            # We also have to pass the details of this gallery to the MyUser datastore
            associate_gallery_to_user = MyUser.get_by_id(myuser_key.id())
            associate_gallery_to_user.gallery_key.append(new_gallery.key)
            associate_gallery_to_user.put()
            self.redirect('/dashboard')

        elif action == 'Edit Gallery':
            # GET CURRENT GALLERY DETAILS
            gallery_key = int(self.request.get('gallery_key'))
            current_gallery = Gallery.get_by_id(gallery_key)

            # GET NEW GALLERY NAME
            new_gallery_name = self.request.get('edit_gallery_name')

            current_gallery.gallery_name = new_gallery_name
            current_gallery.put()
            self.redirect('/')

        elif action == 'Yes':
            # DELETE GALLERY
            gall_id = int(self.request.get('delete_gallery_id'))
            current_gallery = Gallery.get_by_id(gall_id)

            user_info.gallery_key.remove(current_gallery.key)
            user_info.put()
            current_gallery.key.delete()
            self.redirect('/')
예제 #22
0
def main(basepath=None):
	
	if basepath == None:
		if (len(sys.argv) == 2):
			basepath = sys.argv[1]
		else:
			print "Must supply basedir of gallery"
			return False
#			sys.exit(1)
	
	config.read()
	gallery = Gallery(basepath)
	if gallery.scanDirs():
		gallery.deleteIndex()
		gallery.createAlbums()
		
		log("Done.")
예제 #23
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'

        # GET USER KEY
        user = users.get_current_user()
        myuser_key = ndb.Key('MyUser', user.user_id())

        url_id = int(self.request.get('gallery_id_delete'))
        gallery_details = Gallery.get_by_id(url_id)

        # GET NEW IMAGE DETAILS
        image_id = int(self.request.get('image_key'))
        image_details = Image.get_by_id(image_id)

        action = self.request.get('button')

        if action == 'Yes':
            # DELETE PICTURE
            # self.response.write(image_details)
            gallery_details.image_key.remove(image_details.key)
            gallery_details.put()
            image_details.key.delete()
            self.redirect('/gallery?url=' + str(gallery_details.key.urlsafe()))
예제 #24
0
def show_gallery(path):
    global g
    user = g.user
    if user is None and not cfg()["public_access"]:
        return render("gallery.html",
                      authn_error="only logged in users may view this page")
    path = path.encode("utf-8")
    check_jailed_path(path, "data")
    groups = get_access_groups(path)
    if not cfg()["public_access"]:
        if not is_admin_mode(user) and not access_permitted(
                groups, user["groups"]):
            return render("gallery.html", authn_error=True)

    gallery = Gallery(
        path, follow_freedesktop_standard=cfg()["follow_freedesktop_standard"])
    gallery.populate()
    if cfg()["public_access"] or is_admin_mode(user):
        galleries = gallery.get_galleries()
    else:
        galleries = [
            gal for gal in gallery.get_galleries()
            if access_permitted(get_access_groups(gal["key"]), user["groups"])
        ]
    groups_error = None
    if request.method == 'POST':
        action = request.form["action"]
        if action == "save":
            if not is_admin_mode(user):
                return render("gallery.html", authn_error=True)
            groups = request.form["groups_string"].split()
            try:
                set_access_groups(path, groups)
            except IOError, ioe:
                groups_error = "%s" % ioe
        else:
            raise Exception("Unknown gallery editing action: \"%s\"" % action)
예제 #25
0
async def download(
    session,
    gallery_url,
    output_dir="./Images/",
    force_origin=False,
    page_fetcher_num=1,
    page_loader_num=2,
    image_downloader_num=10,
    download_timeout=7.0,
):
    gallery = Gallery.from_url(gallery_url)
    await gallery.load_preview(session)

    planned_pages = asyncio.queues.Queue()
    unloaded_pages = asyncio.queues.Queue()
    loaded_pages = asyncio.queues.Queue()

    async def get_page():
        page_id = await planned_pages.get()
        page = await gallery.get_page(session, page_id)
        await unloaded_pages.put(page)
        planned_pages.task_done()

    async def load_page():
        page = await unloaded_pages.get()
        await page.load(session)
        await loaded_pages.put(page)
        unloaded_pages.task_done()

    async def download_image():
        page = await loaded_pages.get()
        image_url = page.origin_url if force_origin else page.img_url
        print("downloading:", page.page)

        async def failed():
            print("failed:", page.page)
            await unloaded_pages.put(page)

        try:
            data = await ehentai.fetch_data(session, image_url, timeout=download_timeout)
        except asyncio.TimeoutError:
            await failed()
        except aiohttp.BadStatusLine:
            await failed()
        except aiohttp.DisconnectedError:
            await failed()
        except aiohttp.ClientResponseError:
            await failed()
        except aiohttp.ClientOSError:
            await failed()
        else:
            print("done:", page.page)
            open(target_dir + page.img_url.split("/")[-1], "wb").write(data)
        loaded_pages.task_done()

    async def do_forever(job):
        while True:
            try:
                await job()
            except asyncio.CancelledError:
                break
            except:
                import traceback

                traceback.print_exc()

    target_dir = output_dir + gallery.name + "/"
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    for i in range(gallery.page_count):
        await planned_pages.put(i + 1)

    workers = [asyncio.ensure_future(do_forever(get_page)) for __ in range(page_fetcher_num)]
    workers += [asyncio.ensure_future(do_forever(load_page)) for __ in range(page_loader_num)]
    workers += [asyncio.ensure_future(do_forever(download_image)) for __ in range(image_downloader_num)]

    await planned_pages.join()
    # await unloaded_pages and loaded_pages
    while (
        unloaded_pages.qsize() != 0
        or unloaded_pages._unfinished_tasks != 0
        or loaded_pages.qsize() != 0
        or loaded_pages._unfinished_tasks != 0
    ):
        await unloaded_pages.join()
        await loaded_pages.join()

    for worker in workers:
        worker.cancel()
예제 #26
0
def main(_):
    setup_params()
    model = VoxelNet()
    model.build_graph()
    saver = tf.train.Saver()

    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True

    is_val = True
    if is_val:
        db = FLAGS.val_db
        columns = 2  # two columns to visualize groundtruth
    else:
        db = FLAGS.test_db
        columns = 1
        pass

    if FLAGS.results:
        sp.check_call('mkdir -p %s/data' % FLAGS.results, shell=True)

    with tf.Session(config=config) as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        if not FLAGS.test_labels:
            saver.restore(sess, FLAGS.model)

        gal = Gallery('output', cols=columns)
        C = 0
        with open(db, 'r') as f:
            for l in f:
                pk = int(l.strip())
                sample = Sample(pk,
                                LOAD_IMAGE2 | LOAD_VELO | LOAD_LABEL2,
                                is_training=is_val)
                points = sample.get_voxelnet_points()
                points, mask, index = model.vxl.voxelize_points([points], T)
                feed_dict = {
                    model.is_training: False,
                    model.points: points,
                    model.mask: mask,
                    model.index: index
                }

                if is_val:
                    # for validation set, produce the ground-truth boxes
                    boxes_gt = sample.get_voxelnet_boxes(["Car"])
                    #for row in boxes_gt:
                    #    print(row)
                    if FLAGS.test_labels:  # 2 lines below are for testing the C++ code
                        probs, _, params, _ = model.vxl.voxelize_labels(
                            [boxes_gt], np.array(model.priors,
                                                 dtype=np.float32),
                            FLAGS.rpn_stride, FLAGS.lower_th, FLAGS.upper_th)
                    sample.load_voxelnet_boxes(boxes_gt, 'Car')
                    # visualize groundtruth labels
                    image3d = np.copy(sample.image2)
                    for box in sample.label2:
                        draw_box3d(image3d, box, sample.calib)
                        pass
                    cv2.imwrite(gal.next(), image3d)

                if not FLAGS.test_labels:
                    probs, params = sess.run([model.probs, model.params],
                                             feed_dict=feed_dict)

                boxes = model.vxl.generate_boxes(
                    probs, params, np.array(model.priors, dtype=np.float32),
                    FLAGS.anchor_th)
                boxes = cpp.nms(boxes, FLAGS.nms_th)
                boxes = boxes[0]
                #print("++++")
                #for row in boxes:
                #    print(row)
                #print('====')
                print(np.max(probs), len(boxes))
                sample.load_voxelnet_boxes(boxes, 'Car')

                if FLAGS.results:
                    save_label2('%s/data/%06d.txt' % (FLAGS.results, pk),
                                sample.label2)

                image3d = np.copy(sample.image2)
                for box in sample.label2:
                    draw_box3d(image3d, box, sample.calib)
                    pass

                cv2.imwrite(gal.next(), image3d)

                C += 1
                if C >= FLAGS.max:
                    break
                pass
            pass
        gal.flush()
        pass
    pass
예제 #27
0
    def __init__(self, people=0, db=0, mode=0):
        super().__init__()
        self.font = mainfont
        self.resize(700, self.height())
        layout = QGridLayout()
        self.buttext = []

        self.db = db
        self.people = people
        #print(people)
        self.pid = self.people['pid']
        self.edit_people = db.edit_people
        self.mode = mode
        self.gallery = Gallery(self.pid, self.db, mode)
        self.docviewer = DocViewer(self.pid, self.db, self.mode)
        #self.photos = self.gallery.curpixmap
        #print(self.photos)

        self.photo = QPushButton()
        if self.gallery.curpixmap:
            self.pixmap = QPixmap(self.gallery.curpixmap)
            #self.photofile = self.photo
        else:
            self.pixmap = QPixmap(os.path.join('images', 'f.png'))
        self.change_icon()
        self.photo.clicked.connect(self.show_photo)

        self.docs = QPushButton()
        if self.docviewer.docs_ids and type(self.docviewer.docs_ids) == type(
            []) and len(self.docviewer.docs_ids) > 0:
            self.docs_pixmap = QPixmap(os.path.join('images', 'docs.jpg'))
        else:
            self.docs_pixmap = QPixmap(
                os.path.join('images', 'empty_folder.png'))
        self.docs.setIcon(self.docs_pixmap)
        #self.docs.setAlignment(Qt.AlignCenter)
        self.docs.setIconSize(rect.size())
        self.docs.clicked.connect(self.show_docs)

        self.inb = QInvisibleButton(translate('Описание'))
        self.inb.setFont(self.font)
        self.desc = QTextEdit()
        if mode == 0:
            self.desc.setReadOnly(True)
        if 'desc' in people.keys():
            self.desc.setPlainText(people['desc'])

        layout.addWidget(self.photo, 0, 0, len(people.keys()), 1)
        layout.addWidget(self.docs, len(people.keys()) + 2, 0, 1, 1)
        layout.addWidget(self.desc, len(people.keys()) + 2, 1, 1, 1)
        layout.addWidget(self.inb, len(people.keys()) + 2, 1, 1, 1)
        #layout.addWidget(self.eventList, 0, 2, len(people.keys())+3, 1)

        i = 0
        for k, v in self.people.items():
            #	if mode == 0:
            #		if json_people.columns[i] == 'date_end' and str(e) == '':
            #			continue
            #		if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and get_pol(data)[0] == 'м':
            #			continue
            if k == 'desc':
                continue

            lb = QInvisibleButton(translate(k))
            lb.setFont(self.font)
            te = QLineEdit(str(v))
            te.setFont(self.font)
            te.setReadOnly(True)
            self.buttext.append([lb, te])
            #if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and  get_pol(data)[0] == 'м':
            #	continue
            layout.addWidget(te, i, 1, 1, 1)
            layout.addWidget(lb, i, 1, 1, 1)
            if mode:
                te.setReadOnly(False)
                lb.clicked.connect(self.button_pressed)
                te.editingFinished.connect(self.line_edit_finished)
            i = i + 1

        if (mode == 1) or (mode == 2):
            bn = QPushButton('Сохранить')
            bn.setStyleSheet("font-weight: bold; font-size:11pt;")
            #bn.setFont(self.font)
            layout.addWidget(bn, len(people.keys()) + 3, 0, 1, 2)
            #layout.addWidget(bn, 1 , len(json_people.columns) + 1, 1, 1)
            bn.clicked.connect(self.save_press)

        self.setLayout(layout)
예제 #28
0
import thumbnail
from gallery import Gallery

gallery = Gallery()

hooks = {
    'site.start': [thumbnail.create_thumbnails],
    'page.meta.post': [gallery.get_images],
    'page.template.pre': [gallery.get_albums, gallery.set_images],
}
예제 #29
0
#Views
from login import Login
from main import Main
from gallery import Gallery

app = flask.Flask(__name__)
app.secret_key = settings.secret_key


#Routes
app.add_url_rule('/',
                view_func=Main.as_view('main'),
                methods=['GET'])
app.add_url_rule('/<page>/',
                view_func=Main.as_view('main'),
                methods=['GET'])
app.add_url_rule('/gallery/',
                view_func=Gallery.as_view('gallery'),
                methods=['GET'])
app.add_url_rule('/login/',
                view_func=Login.as_view('login'),
                methods=['GET', 'POST'])


@app.errorhandler(404)
def page_not_found(error):
     return flask.render_template('404.html'), 404

app.debug = True
app.run()
예제 #30
0
def main (_):
    global PIXEL_MEANS

    logging.basicConfig(filename='train-%s-%s.log' % (FLAGS.net, datetime.datetime.now().strftime('%Y%m%d-%H%M%S')),level=logging.DEBUG, format='%(asctime)s %(message)s')

    if FLAGS.model:
        try:
            os.makedirs(FLAGS.model)
        except:
            pass

    X = tf.placeholder(tf.float32, shape=(None, None, None, FLAGS.channels), name="images")

    # ground truth labels
    Y = tf.placeholder(tf.int32, shape=(None, None, None, 1), name="labels")
    is_training = tf.placeholder(tf.bool, name="is_training")

    #with \
    #     slim.arg_scope([slim.batch_norm], decay=0.9, epsilon=5e-4): 

    with slim.arg_scope([slim.conv2d, slim.conv2d_transpose, slim.max_pool2d],
                            padding='SAME'), \
                                    slim.arg_scope([slim.conv2d, slim.conv2d_transpose], weights_regularizer=slim.l2_regularizer(2.5e-4), normalizer_fn=slim.batch_norm, normalizer_params={'decay': 0.9, 'epsilon': 5e-4, 'scale': False, 'is_training':is_training}), \
         slim.arg_scope([slim.batch_norm], is_training=is_training):
        logits, FLAGS.stride = getattr(nets, FLAGS.net)(X-PIXEL_MEANS)

    # probability of class 1 -- not very useful if FLAGS.classes > 2
    #probs = tf.squeeze(tf.slice(tf.nn.softmax(logits), [0,0,0,1], [-1,-1,-1,1]), 3)
    probs = tf.squeeze(tf.slice(tf.nn.softmax(logits), [0,0,0,1], [-1,-1,-1,1]), 1)
    loss, metrics = fcn_loss(logits, Y)
    metric_names = [x.name[:-2] for x in metrics]

    def format_metrics (avg):
        return ' '.join(['%s=%.3f' % (a, b) for a, b in zip(metric_names, list(avg))])

    global_step = tf.train.create_global_step()
    LR = tf.train.exponential_decay(FLAGS.lr, global_step, FLAGS.decay_steps, FLAGS.decay_rate, staircase=True)
    if FLAGS.adam:
        print("Using Adam optimizer, reducing LR by 100x")
        optimizer = tf.train.AdamOptimizer(LR/100)
    else:
        optimizer = tf.train.MomentumOptimizer(learning_rate=LR, momentum=0.9)

    train_op = slim.learning.create_train_op(loss, optimizer, global_step=global_step)
    saver = tf.train.Saver(max_to_keep=FLAGS.max_to_keep)

    stream = create_picpac_stream(FLAGS.db, True)
    if FLAGS.gallery:
        gal = Gallery(FLAGS.gallery, ext='.png')
        C = 0 
        for _, images, label  in stream:
            image = images[0]
            print(type(image), image.shape) #, type(anno))
            #print(image.dtype, anno.dtype)
            #print(np.mean(image[:, :, 0]), np.mean(image[:, :, 1]), np.mean(image[:, :, 2]))
            C += 1
            #print('%d / %d' % (C, stream.size()))
            cv2.imwrite(gal.next(), image)
            #cv2.imwrite(gal.next(), anno)
            #cv2.imwrite(gal.next(), label * 255)
            #cv2.imwrite(gal.next(), draw)
            if C == FLAGS.gallery_max:
                break
            pass
        gal.flush()
        sys.exit(0)
    
    # load validation db
    val_stream = None
    if FLAGS.val_db:
        val_stream = create_picpac_stream(FLAGS.val_db, False)

    config = tf.ConfigProto()
    config.gpu_options.allow_growth=True

    epoch_steps = FLAGS.epoch_steps
    if epoch_steps is None:
        epoch_steps = (stream.size() + FLAGS.batch-1) // FLAGS.batch
    best = 0
    with tf.Session(config=config) as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        if FLAGS.resume:
            saver.restore(sess, FLAGS.resume)

        global_start_time = time.time()
        epoch = 0
        step = 0
        while epoch < FLAGS.max_epochs:
            start_time = time.time()
            cnt, metrics_sum = 0, np.array([0] * len(metrics), dtype=np.float32)
            progress = tqdm(range(epoch_steps), leave=False)
            for _ in progress:
                _, images, labels = stream.next()
                #print ("labels:",labels)
                feed_dict = {X: images, Y: labels, is_training: True}
                mm, _ = sess.run([metrics, train_op], feed_dict=feed_dict)
                metrics_sum += np.array(mm) * images.shape[0]
                cnt += images.shape[0]
                metrics_txt = format_metrics(metrics_sum/cnt)
                progress.set_description(metrics_txt)
                step += 1
                pass
            stop = time.time()
            msg = 'train epoch=%d step=%d ' % (epoch, step)
            msg += metrics_txt
            msg += ' elapsed=%.3f time=%.3f ' % (stop - global_start_time, stop - start_time)
            print_green(msg)
            logging.info(msg)

            epoch += 1

            if (epoch % FLAGS.val_epochs == 0) and val_stream:
                lr = sess.run(LR)
                # evaluation
                Ys, Ps = [], []
                cnt, metrics_sum = 0, np.array([0] * len(metrics), dtype=np.float32)
                val_stream.reset()
                progress = tqdm(val_stream, leave=False)
                for _, images, labels in progress:
                    feed_dict = {X: images, Y: labels, is_training: False}
                    p, mm = sess.run([probs, metrics], feed_dict=feed_dict)
                    metrics_sum += np.array(mm) * images.shape[0]
                    cnt += images.shape[0]
                    Ys.extend(list(meta.labels))
                    Ps.extend(list(p))
                    metrics_txt = format_metrics(metrics_sum/cnt)
                    progress.set_description(metrics_txt)
                    pass
                assert cnt == val_stream.size()
                avg = metrics_sum / cnt
                if avg[0] > best:
                    best = avg[0]
                msg = 'valid epoch=%d step=%d ' % (epoch-1, step)
                msg += metrics_txt
                if FLAGS.classes == 2:
                    # display scikit-learn metrics
                    Ys = np.array(Ys, dtype=np.int32)
                    Ps = np.array(Ps, dtype=np.float32)
                    msg += ' sk_acc=%.3f auc=%.3f' % (accuracy_score(Ys, Ps > 0.5), roc_auc_score(Ys, Ps))
                    pass
                msg += ' lr=%.4f best=%.3f' % (lr, best)
                print_red(msg)
                logging.info(msg)
                #log.write('%d\t%s\t%.4f\n' % (epoch, '\t'.join(['%.4f' % x for x in avg]), best))
            # model saving
            if (epoch % FLAGS.ckpt_epochs == 0) and FLAGS.model:
                ckpt_path = '%s/%d' % (FLAGS.model, epoch)
                saver.save(sess, ckpt_path)
                print('saved to %s.' % ckpt_path)
            pass
        pass
    pass
예제 #31
0
 def gallery2(self):
     gallery = Gallery(self)
     gallery.master.title("PiMotionGallery v0.1")
     # gallery.master.maxsize(1024, 750)
     # gallery.master.minsize(1024, 750)
     gallery.mainloop()
예제 #32
0
파일: process.py 프로젝트: youcc/plumo
def main (argv):
    nodule_model = Model(FLAGS.prob, FLAGS.mode, FLAGS.fts, FLAGS.channels, FLAGS.prob_dropout, FLAGS.fts_dropout)
    with open(os.path.join('models', FLAGS.score), 'rb') as f:
        score_model = pickle.load(f)

    case = FsCase(FLAGS.input)

    case.normalizeHU()
    case = case.rescale3D(SPACING)
    lung, _ = mesh.segment_lung(case.images)
    save_mesh(lung, os.path.join(FLAGS.output, 'lung'))
    mask = mesh.convex_hull(lung)
    #body, _ = mesh.segment_body(case.images)
    #save_mesh(body, os.path.join(FLAGS.output, 'body'))
    case.standardize_color()

    case.round_stride(FLAGS.stride)

    mask = case.copy_replace_images(mask)
    mask.round_stride(FLAGS.stride)
    mask = mask.images

    views = [case.transpose(AXIAL),
             case.transpose(SAGITTAL),
             case.transpose(CORONAL)]

    if FLAGS.dilate > 0:
        ksize = FLAGS.dilate * 2 + 1
        mask = grey_dilation(mask, size=(ksize, ksize, ksize), mode='constant')
        pass
    if True:
        with tf.Session() as sess:
            tf.global_variables_initializer().run()
            nodule_model.load(sess)
            dim, nodules = nodule_model.apply(sess, views, mask)
            pass
        pass
    else:
        dim = 11
        nodules = []

    fts = []
    pos = []
    #print(nodules)
    fts.append(pyramid(dim, nodules))   # global
    pos.append(None)                    # global
    for nodule in nodules:
        fts.append(pyramid(dim, [nodule]))
        pos.append(nodule[3])
        pass
    Nt = np.array(fts, dtype=np.float32)
    Ny = score_model.predict_proba(Nt)[:,1]
    global_score = float(Ny[0])
    #print('GLOBAL SCORE:', global_score)
    pw = sorted(zip(pos, list(Ny)), key=lambda x:x[1], reverse=True)

    gal = Gallery(FLAGS.output, cols=5, header=['nodule','score','axial','sagittal','coronal'])
    anno = Annotations()
    C = 1
    for box, score in pw:
        if box is None:
            continue
        if score < 0.1:
            break
        anno.add(box, str(score))
        gal.text('%d' % C)
        gal.text('%.4f' % score)
        for v in VIEWS:
            cc, (y0, x0, y1, x1) = box_center(box, v)
            view = views[v]
            image = get3c(view.images, cc)
            cv2.rectangle(image, (x0,y0), (x1,y1), (0,255,255))
            if v == AXIAL:
                image = cv2.flip(image, 1)
            elif v == SAGITTAL:
                image = cv2.transpose(image)
                image = cv2.flip(image, 0)
            elif v == CORONAL:
                image = cv2.flip(image, -1)
            cv2.imwrite(gal.next(), image)
            pass
        C += 1
        pass
    gal.flush('plumo.html', extra={'score':global_score})
    Papaya(os.path.join(FLAGS.output, 'papaya'), case, annotations=anno)
    pass
예제 #33
0
def main(_):
    X = tf.placeholder(tf.float32,
                       shape=(None, None, None, FLAGS.channels),
                       name="images")
    is_training = tf.placeholder(tf.bool, name="is_training")
    model = Model(X, is_training, FLAGS.model, 'xxx')
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    with tf.Session(config=config) as sess:
        model.loader(sess)
        if FLAGS.input:
            assert False
            '''
            assert os.path.exists(FLAGS.input)
            image = cv2.imread(FLAGS.input, cv2.IMREAD_COLOR)
            batch = np.expand_dims(image, axis=0).astype(dtype=np.float32)
            boxes, probs = sess.run([model.boxes, model.probs], feed_dict={X: batch, is_training: False})
            save_prediction_image(FLAGS.input + '.prob.png', image, boxes, probs)
            '''
        if FLAGS.input_db:
            assert os.path.exists(FLAGS.input_db)
            from gallery import Gallery
            picpac_config = {
                "db":
                FLAGS.input_db,
                "loop":
                False,
                "shuffle":
                False,
                "reshuffle":
                False,
                "annotate":
                False,
                "channels":
                FLAGS.channels,
                "colorspace":
                "RGB",
                "stratify":
                False,
                "dtype":
                "float32",
                "batch":
                1,
                "annotate": [1],
                "transforms": [
                    {
                        "type": "resize",
                        "max_size": FLAGS.max_size
                    },
                    {
                        "type": "clip",
                        "round": FLAGS.backbone_stride
                    },
                    {
                        "type": "keypoints.basic",
                        'downsize': 1,
                        'classes': 1,
                        'radius': 25
                    },
                    {
                        "type": "drop"
                    },  # remove original annotation 
                ]
            }
            stream = picpac.ImageStream(picpac_config)
            gal = Gallery('out')
            C = 0
            for meta, images, _, label, _ in stream:
                shape = list(images.shape)
                shape[1] //= FLAGS.stride
                shape[2] //= FLAGS.stride
                shape[3] = 1
                prob, offsets = sess.run([model.prob, model.offsets],
                                         feed_dict={
                                             X: images,
                                             is_training: False
                                         })
                kp = cpp.predict_basic_keypoints(prob[0], offsets[0],
                                                 FLAGS.stride, 0.1)
                print(images.shape, prob.shape, offsets.shape, kp)
                save_prediction_image(gal.next(), images[0], kp,
                                      label[0, :, :, 0], prob[0, :, :, 0])
                C += 1
                if FLAGS.max and C >= FLAGS.max:
                    break
                pass
            pass
            gal.flush()
    pass
예제 #34
0
def main(_):
    X = tf.placeholder(tf.float32,
                       shape=(None, None, None, FLAGS.channels),
                       name="images")
    model = Model(X, FLAGS.model, 'xxx')
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    with tf.Session(config=config) as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        model.loader(sess)

        gal = Gallery('output', cols=2, ext='.jpg')
        CC = 0
        if FLAGS.list:
            with open(FLAGS.list, 'r') as f:
                for path in f:
                    if CC > FLAGS.max:
                        break
                    path = path.strip()
                    print(path)
                    if FLAGS.channels == 3:
                        image = cv2.imread(path, cv2.IMREAD_COLOR)
                    elif FLAGS.channels == 1:
                        image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
                        image = np.expand_dims(image, axis=3)
                    else:
                        assert False
                    H, W = image.shape[:2]

                    if max(H, W) > FLAGS.max_size:
                        f = FLAGS.max_size / max(H, W)
                        image = cv2.resize(image, None, fx=f, fy=f)
                        H, W = image.shape[:2]
                    '''BEGIN INFERENCE'''
                    # clip edge
                    H = H // FLAGS.clip_stride * FLAGS.clip_stride
                    W = W // FLAGS.clip_stride * FLAGS.clip_stride
                    image = image[:H, :W].astype(np.float32)
                    # change from BGR to RGB
                    if FLAGS.channels == 3 and FLAGS.colorspace == 'RGB':
                        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                        batch = np.expand_dims(image_rgb, axis=0)
                    else:
                        batch = np.expand_dims(image, axis=0)
                    prob = sess.run(model.prob, feed_dict={X: batch})
                    '''END INFERENCE'''
                    save_prediction_image(gal, image, prob[0])
                    CC += 1
        if FLAGS.db:
            stream = picpac.ImageStream({
                'db':
                FLAGS.db,
                'loop':
                False,
                'channels':
                FLAGS.channels,
                'colorspace':
                FLAGS.colorspace,
                'threads':
                1,
                'shuffle':
                False,
                'transforms': [{
                    "type": "resize",
                    "max_size": FLAGS.max_size
                }, {
                    "type": "clip",
                    "round": FLAGS.clip_stride
                }]
            })
            for meta, batch in stream:
                if CC > FLAGS.max:
                    break
                print(meta.ids)
                image = batch[0]
                if FLAGS.channels == 3 and FLAGS.colorspace == 'RGB':
                    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
                prob = sess.run(model.prob, feed_dict={X: batch})
                '''END INFERENCE'''
                save_prediction_image(gal, image, prob[0])
                CC += 1
        gal.flush()
    pass
예제 #35
0
class PersonalCard(QDialog):
    def __init__(self, people=0, db=0, mode=0):
        super().__init__()
        self.font = mainfont
        self.resize(700, self.height())
        layout = QGridLayout()
        self.buttext = []

        self.db = db
        self.people = people
        #print(people)
        self.pid = self.people['pid']
        self.edit_people = db.edit_people
        self.mode = mode
        self.gallery = Gallery(self.pid, self.db, mode)
        self.docviewer = DocViewer(self.pid, self.db, self.mode)
        #self.photos = self.gallery.curpixmap
        #print(self.photos)

        self.photo = QPushButton()
        if self.gallery.curpixmap:
            self.pixmap = QPixmap(self.gallery.curpixmap)
            #self.photofile = self.photo
        else:
            self.pixmap = QPixmap(os.path.join('images', 'f.png'))
        self.change_icon()
        self.photo.clicked.connect(self.show_photo)

        self.docs = QPushButton()
        if self.docviewer.docs_ids and type(self.docviewer.docs_ids) == type(
            []) and len(self.docviewer.docs_ids) > 0:
            self.docs_pixmap = QPixmap(os.path.join('images', 'docs.jpg'))
        else:
            self.docs_pixmap = QPixmap(
                os.path.join('images', 'empty_folder.png'))
        self.docs.setIcon(self.docs_pixmap)
        #self.docs.setAlignment(Qt.AlignCenter)
        self.docs.setIconSize(rect.size())
        self.docs.clicked.connect(self.show_docs)

        self.inb = QInvisibleButton(translate('Описание'))
        self.inb.setFont(self.font)
        self.desc = QTextEdit()
        if mode == 0:
            self.desc.setReadOnly(True)
        if 'desc' in people.keys():
            self.desc.setPlainText(people['desc'])

        layout.addWidget(self.photo, 0, 0, len(people.keys()), 1)
        layout.addWidget(self.docs, len(people.keys()) + 2, 0, 1, 1)
        layout.addWidget(self.desc, len(people.keys()) + 2, 1, 1, 1)
        layout.addWidget(self.inb, len(people.keys()) + 2, 1, 1, 1)
        #layout.addWidget(self.eventList, 0, 2, len(people.keys())+3, 1)

        i = 0
        for k, v in self.people.items():
            #	if mode == 0:
            #		if json_people.columns[i] == 'date_end' and str(e) == '':
            #			continue
            #		if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and get_pol(data)[0] == 'м':
            #			continue
            if k == 'desc':
                continue

            lb = QInvisibleButton(translate(k))
            lb.setFont(self.font)
            te = QLineEdit(str(v))
            te.setFont(self.font)
            te.setReadOnly(True)
            self.buttext.append([lb, te])
            #if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and  get_pol(data)[0] == 'м':
            #	continue
            layout.addWidget(te, i, 1, 1, 1)
            layout.addWidget(lb, i, 1, 1, 1)
            if mode:
                te.setReadOnly(False)
                lb.clicked.connect(self.button_pressed)
                te.editingFinished.connect(self.line_edit_finished)
            i = i + 1

        if (mode == 1) or (mode == 2):
            bn = QPushButton('Сохранить')
            bn.setStyleSheet("font-weight: bold; font-size:11pt;")
            #bn.setFont(self.font)
            layout.addWidget(bn, len(people.keys()) + 3, 0, 1, 2)
            #layout.addWidget(bn, 1 , len(json_people.columns) + 1, 1, 1)
            bn.clicked.connect(self.save_press)

        self.setLayout(layout)

    def save_press(self):
        #sender = self.sender()
        people = {}
        for e in self.buttext:
            people[translate(e[0].text())] = e[1].text()
        people['desc'] = self.desc.toPlainText()
        print(self.edit_people(people))
        self.db.peoples.save()
        self.close()

    def read_binary(self, filename):
        with open(filename, 'rb') as f:
            return f.read()

    def write_binary(self, filename, data):
        with open(filename, 'wb') as f:
            return f.write(data)

    def show_photo(self):
        if self.gallery:
            self.gallery.exec_()
            if self.gallery.curpixmap:
                self.pixmap = QPixmap(self.gallery.curpixmap)
            else:
                self.pixmap = QPixmap(os.path.join('images', 'f.png'))
            self.change_icon()

    def show_docs(self):
        if self.docviewer:
            self.docviewer.exec_()
        if self.docviewer.docs_ids and type(self.docviewer.docs_ids) == type(
            []) and len(self.docviewer.docs_ids) > 0:
            self.docs_pixmap = QPixmap(os.path.join('images', 'docs.jpg'))
        else:
            self.docs_pixmap = QPixmap(
                os.path.join('images', 'empty_folder.png'))
        self.docs.setIcon(self.docs_pixmap)
        self.docs.setIconSize(rect.size())

    def get_exchange_id(self):
        for e in self.buttext:
            if translate(e[0].text()) == 'id':
                return e[1].text()
        return 0

    def change_icon(self):
        self.photo.setIcon(
            self.pixmap.scaled(rect.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
        self.photo.setIconSize(rect.size())

    def photo_load(self):
        dialog = QFileDialog()
        fileNames = []
        if (dialog.exec()):
            fileNames = dialog.selectedFiles()
        if len(fileNames) > 0:
            self.photofile = fileNames[0]
            self.pixmap = QPixmap(self.photofile)
            self.change_icon()

    def button_pressed(self):
        sender = self.sender()
        for b, l in self.buttext:
            if sender == b:
                b.stackUnder(l)
                l.setFocus()

    def line_edit_finished(self):
        sender = self.sender()
        for b, l in self.buttext:
            if sender == l:
                l.stackUnder(b)
                b.setFocus()
예제 #36
0
from reverse import Reverse
from gallery import Gallery

app = flask.Flask(__name__)
app.secret_key = settings.secret_key


#Routes
app.add_url_rule('/',
                view_func=Main.as_view('main'),
                methods=['GET'])
app.add_url_rule('/<page>/',
                view_func=Main.as_view('main'),
                methods=['GET'])
app.add_url_rule('/gallery/',
                view_func=Gallery.as_view('gallery'),
                methods=['GET'])
app.add_url_rule('/login/',
                view_func=Login.as_view('login'),
                methods=['GET', 'POST'])
app.add_url_rule('/remote/',
                view_func=Remote.as_view('remote'),
                methods=['GET', 'POST'])
app.add_url_rule('/reverse/',
                view_func=Reverse.as_view('reverse'),
                methods=['GET', 'POST'])
app.add_url_rule('/music/',
                view_func=Music.as_view('music'),
                methods=['GET'])

@app.errorhandler(404)