Пример #1
0
 def get(self):
     rdic = {}
     source = self.request.get('from', None)
     message = ''
     if source:
         session = Session(self)
         message = session.get('message','')
         session.delete('message')
     rdic['message'] = message
     comments = memcache.get('disqus$comments')
     ua = self.request.headers.get('User-Agent', 'bot')
     path = get_path(ua, 'dashboard.html')
     rdic['notes'] = dbs.Note.getten()
     if comments is not None:
         rdic['comments'] = comments
         return self.response.out.write(render(path,rdic))
     disqus_key = dbs.Vigo.get('disqus_key')
     disqus_forumid = dbs.Vigo.get('disqus_forumid')
     mydisqus = Disqus(disqus_key)
     mydisqus.get_forum_posts_rpc(disqus_forumid)
     result = mydisqus.get_forum_posts_result()
     comments = mydisqus.parse_data(result)
     memcache.set('god$comments', comments, 10800) # 3 hours
     rdic['comments'] = comments
     return self.response.out.write(render(path,rdic))
Пример #2
0
def main(args):
    # Init TDDFA
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)
    gpu_mode = args.mode == 'gpu'
    tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)

    # Init FaceBoxes
    face_boxes = FaceBoxes()

    # Given a still image path and load to BGR channel
    img = cv2.imread(args.img_fp)

    # Detect faces, get 3DMM params and roi boxes
    boxes = face_boxes(img)
    n = len(boxes)
    print(f'Detect {n} faces')
    if n == 0:
        print(f'No face detected, exit')
        sys.exit(-1)

    param_lst, roi_box_lst = tddfa(img, boxes)

    # Visualization and serialization
    dense_flag = args.opt in ('2d_dense', '3d', 'depth', 'pncc', 'uv_tex', 'ply', 'obj')
    old_suffix = get_suffix(args.img_fp)
    new_suffix = f'.{args.opt}' if args.opt in ('ply', 'obj') else '.jpg'

    wfp = f'examples/results/{args.img_fp.split("/")[-1].replace(old_suffix, "")}_{args.opt}' + new_suffix

    ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)

    if args.opt == '2d_sparse':
        draw_landmarks(img, ver_lst, show_flag=args.show_flag, dense_flag=dense_flag, wfp=wfp)
    elif args.opt == '2d_dense':
        draw_landmarks(img, ver_lst, show_flag=args.show_flag, dense_flag=dense_flag, wfp=wfp)
    elif args.opt == '3d':
        render(img, ver_lst, alpha=0.6, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'depth':
        # if `with_bf_flag` is False, the background is black
        depth(img, ver_lst, show_flag=args.show_flag, wfp=wfp, with_bg_flag=True)
    elif args.opt == 'pncc':
        pncc(img, ver_lst, show_flag=args.show_flag, wfp=wfp, with_bg_flag=True)
    elif args.opt == 'uv_tex':
        uv_tex(img, ver_lst, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'pose':
        viz_pose(img, param_lst, ver_lst, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'ply':
        ser_to_ply(ver_lst, height=img.shape[0], wfp=wfp)
    elif args.opt == 'obj':
        ser_to_obj(img, ver_lst, height=img.shape[0], wfp=wfp)
    else:
        raise ValueError(f'Unknown opt {args.opt}')
Пример #3
0
 def get(self):
     rdic = {}
     rdic['navs'] = get_navs()
     p = self.request.get('p',1)
     keys = dbs.Article.show_keys()
     mvdata = dbs.Article.get_page(keys, p)
     if mvdata['page'] > mvdata['page_num']:
         path = get_path(self.is_mobile, '404.html')
         self.response.set_status(404)
         html = render(path, rdic)
         return self.response.out.write(html)
     rdic['mvdata'] = mvdata
     path = get_path(self.is_mobile, 'archive.html')
     self.response.out.write(render(path,rdic))
Пример #4
0
def main(args):
    # Init TDDFA
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)
    gpu_mode = args.mode == 'gpu'
    tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)

    # Init FaceBoxes
    face_boxes = FaceBoxes()

    # Given a still image path and load to BGR channel
    img = cv2.imread(args.img_fp)

    # Detect faces, get 3DMM params and roi boxes
    boxes = face_boxes(img)
    n = len(boxes)
    print(f'Detect {n} faces')
    if n == 0:
        print(f'No face detected, exit')
        sys.exit(-1)

    param_lst, roi_box_lst = tddfa(img, boxes)

    # Visualization and serialization
    dense_flag = args.opt in (
        '2d_dense', '3d', 'depth'
    )  # if opt is 2d_dense or 3d, reconstruct dense vertices
    ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)

    suffix = get_suffix(args.img_fp)
    wfp = f'examples/results/{args.img_fp.split("/")[-1].replace(suffix, "")}_{args.opt}.jpg'

    if args.opt == '2d_sparse':
        draw_landmarks(img,
                       ver_lst,
                       show_flag=args.show_flag,
                       dense_flag=dense_flag,
                       wfp=wfp)
    elif args.opt == '2d_dense':
        draw_landmarks(img,
                       ver_lst,
                       show_flag=args.show_flag,
                       dense_flag=dense_flag,
                       wfp=wfp)
    elif args.opt == '3d':
        render(img, ver_lst, alpha=0.6, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'depth':
        depth(img, ver_lst, show_flag=args.show_flag, wfp=wfp)
    else:
        raise Exception(f'Unknown opt {args.opt}')
Пример #5
0
 def get(self, slug):
     ua = self.request.headers.get('User-Agent', 'bot')
     rdic = {}
     data = dbs.Note.get(slug)
     if not data:
         logging.info('404 , visite note ' + str(slug))
         path = get_path(ua, '404.html')
         self.response.set_status(404)
         html = render(path, rdic)
         return self.response.out.write(html)
     rdic['navs'] = dbs.Melody.get_all('nav')
     rdic['data'] = data
     path = get_path(ua, 'note.html')
     html = render(path, rdic)
     self.response.out.write(html)
Пример #6
0
def main_s(args):
    global tddfa
    global face_boxes
    # Given a still image path and load to BGR channel
    img = cv2.imread(args.img_fp)

    # Detect faces, get 3DMM params and roi boxes
    boxes = face_boxes(img)
    n = len(boxes)
    if n == 0:
        print(f'No face detected, exit')
        return
        #sys.exit(-1)
    print(f'Detect {n} faces')

    param_lst, roi_box_lst = tddfa(img, boxes)

    # Visualization and serialization
    dense_flag = args.opt in ('2d_dense', '3d', 'depth', 'pncc', 'uv_tex', 'ply', 'obj')
    old_suffix = get_suffix(args.img_fp)
    new_suffix = f'.{args.opt}' if args.opt in ('ply', 'obj') else '.jpg'

    wfp = f'examples/results/{args.img_fp.split("/")[-1].replace(old_suffix, "")}_{args.opt}' + new_suffix

    ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)
    # print(len(ver_lst),ver_lst[0].shape)
    if args.opt == '3d':
        viz_pose(img, param_lst, ver_lst, show_flag=args.show_flag, wfp=wfp)
        return render(img, ver_lst, tddfa.tri, alpha=0.6, show_flag=args.show_flag, wfp=wfp)
    else:
        raise ValueError(f'Unknown opt {args.opt}')
Пример #7
0
 def get(self, slug):
     slug = self.unquote(slug)
     data = dbs.Page.get_by_slug(slug)
     rdic = {}
     rdic['navs'] = get_navs()
     rdic['links'] = dbs.Melody.get_all('link')
     if not data:
         logging.info('404 , visite page ' + slug)
         path = get_path(self.is_mobile, '404.html')
         self.response.set_status(404)
         html = render(path, rdic)
         return self.response.out.write(html)
     rdic['data'] = data
     path = get_path(self.is_mobile, 'page.html')
     html = render(path, rdic)
     self.response.out.write(html)
Пример #8
0
 def get(self):
     logging.info('404')
     rdic = {}
     ua = self.request.headers.get('User-Agent', 'bot')
     path = get_path(ua, '404.html')
     self.response.set_status(404)
     self.response.out.write(render(path,rdic))
Пример #9
0
 def get(self, username):
     rdic = {}
     rdic['navs'] = get_navs()
     rdic['links'] = dbs.Melody.get_all('link')
     rdic['tweets'] = self.tweets(username)
     path = get_path(self.request, 'utils_twitter.html')
     self.response.out.write(render(path,rdic))
Пример #10
0
 def get(self):
     source = self.request.get('from', None)
     message = ''
     if source:
         message = self.session.get('message','')
         self.session.delete('message')
     rdic = {}
     action = self.request.get('action', 'none').lower()
     key = self.request.get('key', 'none')
     status = self.request.get('draft', '2')
     if 'draft' == action or 'post' == action:
         data = db.get(key)
         if data and 'draft' == action:
             data.sw_status(data)
         elif data and 'post' == action:
             data.sw_status(data, False)
         else:
             self.session['message'] = "Can't find the article"
         return self.redirect('/god/article?from='+action)
     if 'filter' == action:
         data = self.get_filter(status)
     elif 'find' == action:
         data = self.get_find(key)
         if data:
             return self.redirect('/god/article/edit?key=%s' % data.key())
         message = "Not find the article"
         data = dbs.Article.gql('ORDER BY created DESC')
     else:
         data = dbs.Article.gql('ORDER BY created DESC')
     rdic['message'] = message
     p = self.request.get('p',1)
     rdic['mvdata'] = Paginator(data, count, p)
     path = get_tpl('article.html')
     return self.response.out.write(render(path,rdic))
Пример #11
0
 def get(self):
     path = get_tpl('twitter_user.html')
     rdic = {}
     source = self.request.get('from', None)
     message = ''
     if source:
         message = self.session.get('message','')
         self.session.delete('message')
     rdic['message'] = message
     qs = dbs.Vigo.get('oauth_twitter')
     if not qs:
         return self.redirect('/god/twitter/login')
     api = Twitter().set_qs_api(qs)
     statuses = memcache.get('twitter$home')
     if statuses is None:
         statuses = api.GetFriendsTimeline(count=30, retweets=True)
         for status in statuses:
             status.datetime = datetime.datetime.strptime(status.created_at, '%a %b %d %H:%M:%S +0000 %Y')
         memcache.set('twitter$home', statuses, 240)
     rdic['statuses'] = statuses
     username = dbs.Vigo.get('twitter')
     profile = memcache.get('twitter$profile$' + username)
     if profile is None:
         profile = api.GetUser(username)
         memcache.set('twitter$profile$'+username, profile, 86400)
     rdic['profile'] = profile
     rdic['username'] = username
     return self.response.out.write(render(path, rdic))
Пример #12
0
 def post(self):
     rdic = {}
     key = self.request.get('key', None)
     if not key:
         return self.redirect('/god/article')
     data = db.get(key)
     if not data:
         return self.redirect('/god/article')
     title = self.request.get('title', None)
     slug = self.request.get('slug', None)
     text = self.request.get('text', None)
     draft = self.request.get('draft', None)
     keyword = self.request.get('keyword', None)
     if draft:
         draft = True
     else:
         draft = False
     if title and slug:
         dbs.Article.update(data, title, slug, text, draft, keyword)
         session = Session(self)
         session['message'] = 'Article <a href="/god/article/edit?key=%s">%s</a> has been modified' % (data.key(), data.title)
         return self.redirect('/god/article?from=edit')
     rdic['data'] = data
     message = 'Please fill the required fields'
     rdic['message'] = message
     ua = self.request.headers.get('User-Agent', 'bot')
     path = get_path(ua, 'edit_article.html')
     return self.response.out.write(render(path,rdic))
Пример #13
0
 def post(self):
     rdic = {}
     key = self.request.get("key", None)
     if not key:
         return self.redirect("/god/melody")
     data = dbs.get_by_key(key)
     if not data:
         return self.redirect("/god/melody")
     label = self.request.get("label", None)
     title = self.request.get("title", None)
     url = self.request.get("url", None)
     prior = self.request.get("prior", 0)
     text = self.request.get("text", None)
     ext = self.request.get("ext", None)
     if title and label:
         try:
             prior = int(prior)
         except:
             prior = 0
         data.update(title, url, label, prior, ext, text)
         self.session["message"] = '%s <a href="/god/melody/edit?key=%s">%s</a> has been modified' % (
             data.label.upper(),
             data.key(),
             data.title,
         )
         return self.redirect("/god/melody?from=edit")
     rdic["data"] = data
     message = "Please fill the required fields"
     rdic["message"] = message
     path = get_tpl("edit_melody.html")
     return self.response.out.write(render(path, rdic))
Пример #14
0
 def post(self):
     rdic = {}
     key = self.request.get('key', None)
     p = self.request.get('p', 1)
     to = '/god/article?p=%s' % p
     if not key:
         return self.redirect(to)
     data = dbs.get_by_key(key)
     if not data:
         return self.redirect(to)
     title = self.request.get('title', None)
     slug = self.request.get('slug', None)
     text = self.request.get('text', None)
     draft = self.request.get('draft', None)
     keyword = self.request.get('keyword', None)
     if draft:
         draft = True
     else:
         draft = False
     if title and slug:
         data.update(title, slug, text, draft, keyword)
         self.session['message'] = 'Article <a href="/god/article/edit?key=%s">%s</a> has been modified' % (data.key(), data.title)
         if not draft:
             taskqueue.add(url='/god/task/ping', method="GET")
         return self.redirect(to + ';from=edit')
     rdic['data'] = data
     message = 'Please fill the required fields'
     rdic['message'] = message
     path = get_tpl('edit_article.html')
     return self.response.out.write(render(path,rdic))
Пример #15
0
 def post(self):
     rdic = {}
     title = self.request.get("title", None)
     slug = self.request.get("slug", None)
     text = self.request.get("text", None)
     keyword = self.request.get("keyword", None)
     draft = self.request.get("draft", None)
     if draft:
         draft = True
     else:
         draft = False
     if title and slug:
         data = dbs.Article.add(title, slug, text, draft, keyword)
         self.session["message"] = 'New article <a href="/god/article/edit?key=%s">%s</a> has been created' % (
             data.key(),
             data.title,
         )
         if not draft:
             self.tweet(data)
             taskqueue.add(url="/god/task/ping", method="GET")
         return self.redirect("/god/article?from=add")
     message = "Please fill the required fields"
     rdic["message"] = message
     path = get_tpl("add_article.html")
     return self.response.out.write(render(path, rdic))
Пример #16
0
 def post(self):
     rdic = {}
     key = self.request.get('key', None)
     if not key:
         return self.redirect('/god/melody')
     data = dbs.get_by_key(key)
     if not data:
         return self.redirect('/god/melody')
     label = self.request.get('label', None)
     title = self.request.get('title', None)
     url = self.request.get('url', None)
     prior = self.request.get('prior',0)
     text = self.request.get('text', None)
     ext = self.request.get('ext', None)
     if title and label:
         try: prior = int(prior)
         except: prior = 0
         data.update(title,url,label,prior,ext,text)
         self.session['message'] = '%s <a href="/god/melody/edit?key=%s">%s</a> has been modified' % (data.label.upper(), data.key(), data.title)
         return self.redirect('/god/melody?from=edit')
     rdic['data'] = data
     message = 'Please fill the required fields'
     rdic['message'] = message
     path = get_tpl('edit_melody.html')
     return self.response.out.write(render(path,rdic))
Пример #17
0
 def post(self):
     rdic = {}
     key = self.request.get("key", None)
     p = self.request.get("p", 1)
     to = "/god/article?p=%s" % p
     if not key:
         return self.redirect(to)
     data = dbs.get_by_key(key)
     if not data:
         return self.redirect(to)
     title = self.request.get("title", None)
     slug = self.request.get("slug", None)
     text = self.request.get("text", None)
     draft = self.request.get("draft", None)
     keyword = self.request.get("keyword", None)
     if draft:
         draft = True
     else:
         draft = False
     if title and slug:
         data.update(title, slug, text, draft, keyword)
         self.session["message"] = 'Article <a href="/god/article/edit?key=%s">%s</a> has been modified' % (
             data.key(),
             data.title,
         )
         if not draft:
             taskqueue.add(url="/god/task/ping", method="GET")
         return self.redirect(to + ";from=edit")
     rdic["data"] = data
     message = "Please fill the required fields"
     rdic["message"] = message
     path = get_tpl("edit_article.html")
     return self.response.out.write(render(path, rdic))
Пример #18
0
    def post(self):
        rdic = {}
        sitename = self.request.get('sitename', 'Vealous')
        sitetag = self.request.get('sitetag', 'Pure Vealous')
        twitter = self.request.get('twitter', 'lepture')
        ga = self.request.get('ga','')
        gcse = self.request.get('gcse','')
        disqus = self.request.get('disqus','')
        disqus_key = self.request.get('disqus_key','')
        forum_key = self.request.get('forum_key','')
        disqus_forumid = self.request.get('disqus_forumid','')
        alterfeed = self.request.get('alterfeed','')

        rdic['sitename'] = dbs.Vigo.set('sitename', sitename)
        rdic['sitetag'] = dbs.Vigo.set('sitetag', sitetag)
        rdic['twitter'] = dbs.Vigo.set('twitter', twitter)
        rdic['ga'] = dbs.Vigo.set('ga', ga)
        rdic['gcse'] = dbs.Vigo.set('gcse', gcse)
        rdic['disqus'] = dbs.Vigo.set('disqus', disqus)
        rdic['disqus_key'] = dbs.Vigo.set('disqus_key', disqus_key)
        rdic['forum_key'] = dbs.Vigo.set('forum_key', forum_key)
        rdic['disqus_forumid'] = dbs.Vigo.set('disqus_forumid', disqus_forumid)
        rdic['alterfeed'] = dbs.Vigo.set('alterfeed', alterfeed)
        memcache.delete('vigo')
        rdic['message'] = 'Your setting has been saved'
        ua = self.request.headers.get('User-Agent', 'bot')
        path = get_path(ua, 'vigo.html')
        return self.response.out.write(render(path,rdic))
Пример #19
0
 def get(self):
     ua = self.request.headers.get('User-Agent', 'bot')
     path = get_path(ua, 'douban_dashboard.html')
     rdic = {}
     source = self.request.get('from', None)
     message = ''
     if source:
         session = Session(self)
         message = session.get('message','')
         session.delete('message')
     rdic['message'] = message
     qs = dbs.Vigo.get('oauth_douban')
     if not qs:
         return self.redirect('/god/douban/login')
     api = pydouban.Api()
     api.set_qs_oauth(config.douban_key, config.douban_secret, qs)
     profile = memcache.get('douban/profile')
     if profile is None:
         profile = api.get_profile()
         memcache.set('douban/profile', profile, day)
     rdic['profile'] = profile
     miniblogs = memcache.get('douban/miniblogs')
     if miniblogs is None:
         miniblogs = api.get_contacts_miniblog()
         for i in range(len(miniblogs.entry)):
             miniblogs.entry[i].published.t = datetime.datetime.strptime(
                 miniblogs.entry[i].published.t, '%Y-%m-%dT%H:%M:%S+08:00')
             miniblogs.entry[i].published.t -= datetime.timedelta(hours=8)
         memcache.set('douban/miniblogs', miniblogs, 240)
     rdic['miniblogs'] = miniblogs
     return self.response.out.write(render(path, rdic))
Пример #20
0
def main(args):
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)
    gpu_mode = args.mode == 'gpu'
    tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)

    # Initialize FaceBoxes
    face_boxes = FaceBoxes()

    # Given a video path
    fn = args.video_fp.split('/')[-1]
    reader = imageio.get_reader(args.video_fp)

    fps = reader.get_meta_data()['fps']

    suffix = get_suffix(args.video_fp)
    video_wfp = f'examples/results/videos/{fn.replace(suffix, "")}_{args.opt}.mp4'
    writer = imageio.get_writer(video_wfp, fps=fps)

    # run
    dense_flag = args.opt in ('3d',)
    pre_ver = None
    for i, frame in tqdm(enumerate(reader)):
        frame_bgr = frame[..., ::-1]  # RGB->BGR

        if i == 0:
            # the first frame, detect face, here we only use the first face, you can change depending on your need
            boxes = face_boxes(frame_bgr)
            boxes = [boxes[0]]
            param_lst, roi_box_lst = tddfa(frame_bgr, boxes)
            ver = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)[0]

            # refine
            param_lst, roi_box_lst = tddfa(frame_bgr, [ver], crop_policy='landmark')
            ver = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)[0]
        else:
            param_lst, roi_box_lst = tddfa(frame_bgr, [pre_ver], crop_policy='landmark')

            roi_box = roi_box_lst[0]
            # todo: add confidence threshold to judge the tracking is failed
            if abs(roi_box[2] - roi_box[0]) * abs(roi_box[3] - roi_box[1]) < 2020:
                boxes = face_boxes(frame_bgr)
                boxes = [boxes[0]]
                param_lst, roi_box_lst = tddfa(frame_bgr, boxes)

            ver = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)[0]

        pre_ver = ver  # for tracking

        if args.opt == '2d':
            res = cv_draw_landmark(frame_bgr, ver)
        elif args.opt == '3d':
            res = render(frame_bgr, [ver])
        else:
            raise Exception(f'Unknown opt {args.opt}')

        writer.append_data(res[..., ::-1])  # BGR->RGB

    writer.close()
    print(f'Dump to {video_wfp}')
Пример #21
0
    def post(self, eventid):
        # We use locals() which confuses pylint.
        # pylint: disable-msg=W0612
        ####################################################
        event = models.Event.get_by_id(long(eventid))
        if not event:
            self.redirect('/')
        current_user = users.get_current_user()
        if not current_user:
            self.redirect('/')
            return
        ####################################################

        response, guests = event_lists.get_event_responses(event, current_user)
        
        # Check if the person is trying to add friends
        try:
            extra_guests = range(
                0, int(self.request.get('friends', '0'))-len(guests))
        except ValueError:
            extra_guests = []

        if extra_guests:
            self.response.out.write(render(
                    'templates/response-friends.html', locals()))
            return
    
        # Remove the current information
        if response is not None:
            response.delete()
        for guest in guests:
            guest.delete()

        response = models.Response(event=event, gcreated_by = current_user,
                guest=False)
        response.attending = self.request.get('attending').lower() != 'no'
        response.put()

        logging.info('Response %s created by user %s (email: %s fedid: %s)',
                response.key(), current_user.nickname(), current_user.email(),
                current_user.federated_identity() )

        guest_names = self.request.get_all('guest_name')
        guest_emails = self.request.get_all('guest_email')
        assert len(guest_names) == len(guest_emails)

        for name, email in zip(guest_names, guest_emails):
            name, email = name.strip(), email.strip()
            if not name or not email:
                continue

            response = models.Response(event=event, guest=True,
                    gcreated_by = current_user)
            response.attending = True
            response.guest_name = name
            response.guest_email = email
            response.put()

        self.redirect('/event/%s/response/show' % event.key().id())
Пример #22
0
 def get(self):
     rdic = {}
     rdic['disqus_key'] = dbs.Vigo.get('disqus_key')
     rdic['forum_key'] = dbs.Vigo.get('forum_key')
     rdic['disqus_forumid'] = dbs.Vigo.get('disqus_forumid')
     ua = self.request.headers.get('User-Agent', 'bot')
     path = get_path(ua, 'vigo.html')
     return self.response.out.write(render(path,rdic))
Пример #23
0
 def get(self, keyword):
     ua = self.request.headers.get('User-Agent', 'bot')
     rdic = {}
     articles = dbs.Article.keyword_article(keyword)
     if not articles:
         logging.info('404 , visite keyword ' + str(keyword))
         path = get_path(ua, '404.html')
         html = render(path, rdic)
         self.response.set_status(404)
     else:
         rdic['articles'] = articles
         rdic['navs'] = dbs.Melody.get_all('nav')
         rdic['links'] = dbs.Melody.get_all('link')
         rdic['keyword'] = keyword
         path = get_path(ua, 'keyword.html')
         html = render(path, rdic)
     self.response.out.write(html)
Пример #24
0
 def get(self):
     rdic = {}
     rdic['navs'] = get_navs()
     p = self.request.get('p',1)
     keys = dbs.Article.show_keys()
     rdic['mvdata'] = dbs.Article.get_page(keys, p)
     path = get_path(self.is_mobile, 'archive.html')
     self.response.out.write(render(path,rdic))
Пример #25
0
def inference(img):
    # face detection
    boxes = face_boxes(img)
    # regress 3DMM params
    param_lst, roi_box_lst = tddfa(img, boxes)
    # reconstruct vertices and render
    ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=True)
    return render(img, ver_lst, tddfa.tri, alpha=0.6, show_flag=False)
Пример #26
0
 def get(self):
     rdic = {}
     rdic['navs'] = get_navs()
     p = self.request.get('p',1)
     data = dbs.Article.get_archive()
     rdic['mvdata'] = Paginator(data, 10, p)
     path = get_path(self.request, 'archive.html')
     self.response.out.write(render(path,rdic))
Пример #27
0
 def get(self, keyword):
     keyword = safeunquote(keyword)
     rdic = {}
     data = dbs.Article.get_kw_articles(keyword)
     if not data:
         logging.info('404 , visite keyword ' + keyword)
         path = get_path(self.request, '404.html')
         html = render(path, rdic)
         self.response.set_status(404)
     else:
         p = self.request.get('p',1)
         rdic['mvdata'] = Paginator(data, 10, p)
         rdic['navs'] = get_navs()
         rdic['links'] = dbs.Melody.get_all('link')
         rdic['keyword'] = keyword
         path = get_path(self.request, 'keyword.html')
         html = render(path, rdic)
     self.response.out.write(html)
Пример #28
0
 def get(self, keyword):
     keyword = self.unquote(keyword)
     rdic = {}
     keys = dbs.Article.kw_keys(keyword)
     if not keys:
         logging.info('404 , visite keyword ' + keyword)
         path = get_path(self.is_mobile, '404.html')
         html = render(path, rdic)
         self.response.set_status(404)
         return self.response.out.write(html)
     p = self.request.get('p',1)
     rdic['mvdata'] = dbs.Article.get_page(keys, p)
     rdic['navs'] = get_navs()
     rdic['links'] = dbs.Melody.get_all('link')
     rdic['keyword'] = keyword
     path = get_path(self.is_mobile, 'keyword.html')
     html = render(path, rdic)
     self.response.out.write(html)
Пример #29
0
 def get(self):
     rdic = {}
     rdic['notes'] = dbs.Note.getten()
     rdic['articles'] = dbs.Article.getten()
     rdic['navs'] = dbs.Melody.get_all('nav')
     rdic['links'] = dbs.Melody.get_all('link')
     ua = self.request.headers.get('User-Agent', 'bot')
     path = get_path(ua, 'index.html')
     self.response.out.write(render(path,rdic))
Пример #30
0
 def get(self):
     rdic = {}
     p = self.request.get('p',1)
     rdic['navs'] = get_navs()
     rdic['links'] = dbs.Melody.get_all('link')
     data = dbs.DictBook.get_all()
     rdic['mvdata'] = Paginator(data, 30, p)
     path = get_path(self.request, 'utils_dict.html')
     self.response.out.write(render(path,rdic))
Пример #31
0
 def get(self):
     rdic = {}
     rdic['navs'] = dbs.Melody.get_all('nav')
     ua = self.request.headers.get('User-Agent', 'bot')
     p = self.request.get('p',1)
     q = dbs.Article.gql("WHERE draft = :1 ORDER BY created DESC", False)
     rdic['mvdata'] = Paginator(q, 10, p)
     path = get_path(ua, 'archive.html')
     self.response.out.write(render(path,rdic))
Пример #32
0
 def get(self):
     auth = self.session.get("auth", 0)
     gauth = users.is_current_user_admin()
     if 1 == auth or gauth:
         self.redirect("/god")
     rdic = {}
     path = get_path(self.request, "login.html")
     rdic["gurl"] = users.create_login_url(self.request.url)
     return self.response.out.write(render(path, rdic))
Пример #33
0
 def get(self):
     auth = self.session.get('auth',0)
     gauth = users.is_current_user_admin()
     if 1 == auth or gauth:
         self.redirect('/god')
     rdic = {}
     path = get_path(self.request, 'login.html')
     rdic['gurl'] = users.create_login_url(self.request.url)
     return self.response.out.write(render(path,rdic))
Пример #34
0
 def get(self):
     self.response.headers['Content-Type'] = 'text/xml; charset=UTF-8'
     html = memcache.get('xml$rss')
     if html is None:
         rdic = {}
         rdic['datas'] = dbs.Article.getten()
         path = os.path.join(config.ROOT, 'tpl', 'rss.xml')
         html = render(path, rdic)
         memcache.set('xml$rss', html)
     self.response.out.write(html)
Пример #35
0
 def get(self, slug):
     slug = safeunquote(slug)
     rdic = {}
     data = dbs.Article.get(slug)
     if not data:
         logging.info('404 , visite article ' + slug)
         path = get_path(self.request, '404.html')
         self.response.set_status(404)
         html = render(path, rdic)
         return self.response.out.write(html)
     mode = self.request.get('mode','mark')
     if 'plaintext' == mode:
         self.response.headers['Content-Type'] = 'text/plain; charset=UTF-8'
         html = data.text
         return self.response.out.write(html)
     rdic['navs'] = get_navs()
     rdic['data'] = data
     path = get_path(self.request, 'article.html')
     html = render(path, rdic)
     self.response.out.write(html)
Пример #36
0
strength = multiply(r, yfac)
ems = emission(color, strength)

as_volume(ems)

cube.data.materials.append(orbital_mat)

# animation

anim(ythr, -1.2, 0)
anim(ythr, -1.2, 10)
anim(ythr, 1.2, 60)
anim(ythr, 1.2, 120)
anim(ythr, -1.2, 180)
anim(ythr, -1.2, 200)

# sky
colorSky((0.01, 0.01, 0.02, 1))

# camera
camera = bpy.data.objects['Camera']
camera.location = (0, 12.5, 0)
camera.rotation_euler = (pi / 2, 0, pi)

# render image
bpy.context.scene.camera = camera
bpy.context.scene.frame_end = 200

render('orb', 0.2, False)
Пример #37
0
orbital_mat = node_material()

location = location()
time = time(200, 0.05)

re, im = osl_script('orbital/orb_11', location, time)
r, phi = polar(re, im)
norm_phi = multiply_by(phi, 1 / (2*pi))
hue = fract(norm_phi)
color = hue_ramp(hue)
strength = multiply_by(r, 0.5)
ems = emission(color, strength)

as_volume(ems)

cube.data.materials.append(orbital_mat)

# sky
colorSky((0.01, 0.01, 0.02, 1))

# camera
camera = bpy.data.objects['Camera']
camera.location = (15,0,0)
camera.rotation_euler = (pi/2,0,pi/2)

# render image
bpy.context.scene.camera = camera
bpy.context.scene.frame_end = 200

render('orb11', 0.02, True)
        
Пример #38
0
{
    if (inside) { c = color(0); }
    else        { c = out; }
}
'''

(color, ) = inn_script(s2, inside, out_color)

strength = value(1)
ems = emission(color, strength)

as_surface(ems)

plane.data.materials.append(julia_mat)

# animation

anim(alpha, 0, 0)
anim(alpha, 2*pi, 100)

# camera
camera = bpy.data.objects['Camera']
camera.location = (0,0,8)
camera.rotation_euler = (0,0,0)

# render image
bpy.context.scene.camera = camera
bpy.context.scene.frame_end = 100

render('julia_' + shader + ('_l' if withLight else ''), 0.6, False)
        
Пример #39
0
def main(args):
    # Init TDDFA or TDDFA_ONNX
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)
    if args.onnx:
        from TDDFA_ONNX import TDDFA_ONNX
        tddfa = TDDFA_ONNX(**cfg)
    else:
        gpu_mode = args.mode == 'gpu'
        tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)

    # Initialize FaceBoxes
    face_boxes = FaceBoxes()

    # Given a video path
    fn = args.video_fp.split('/')[-1]
    reader = imageio.get_reader(args.video_fp)

    fps = reader.get_meta_data()['fps']
    suffix = get_suffix(args.video_fp)
    video_wfp = f'examples/results/videos/{fn.replace(suffix, "")}_{args.opt}_smooth.mp4'
    writer = imageio.get_writer(video_wfp, fps=fps)

    # the simple implementation of average smoothing by looking ahead by n_next frames
    # assert the frames of the video >= n
    n_pre, n_next = args.n_pre, args.n_next
    n = n_pre + n_next + 1
    queue_ver = deque()
    queue_frame = deque()

    # run
    dense_flag = args.opt in (
        '2d_dense',
        '3d',
    )
    pre_ver = None
    for i, frame in tqdm(enumerate(reader)):
        if args.start > 0 and i < args.start:
            continue
        if args.end > 0 and i > args.end:
            break

        frame_bgr = frame[..., ::-1]  # RGB->BGR

        if i == 0:
            # detect
            boxes = face_boxes(frame_bgr)
            boxes = [boxes[0]]
            param_lst, roi_box_lst = tddfa(frame_bgr, boxes)
            ver = tddfa.recon_vers(param_lst,
                                   roi_box_lst,
                                   dense_flag=dense_flag)[0]

            # refine
            param_lst, roi_box_lst = tddfa(frame_bgr, [ver],
                                           crop_policy='landmark')
            ver = tddfa.recon_vers(param_lst,
                                   roi_box_lst,
                                   dense_flag=dense_flag)[0]

            # padding queue
            for _ in range(n_pre):
                queue_ver.append(ver.copy())
            queue_ver.append(ver.copy())

            for _ in range(n_pre):
                queue_frame.append(frame_bgr.copy())
            queue_frame.append(frame_bgr.copy())

        else:
            param_lst, roi_box_lst = tddfa(frame_bgr, [pre_ver],
                                           crop_policy='landmark')

            roi_box = roi_box_lst[0]
            # todo: add confidence threshold to judge the tracking is failed
            if abs(roi_box[2] - roi_box[0]) * abs(roi_box[3] -
                                                  roi_box[1]) < 2020:
                boxes = face_boxes(frame_bgr)
                boxes = [boxes[0]]
                param_lst, roi_box_lst = tddfa(frame_bgr, boxes)

            ver = tddfa.recon_vers(param_lst,
                                   roi_box_lst,
                                   dense_flag=dense_flag)[0]

            queue_ver.append(ver.copy())
            queue_frame.append(frame_bgr.copy())

        pre_ver = ver  # for tracking

        # smoothing: enqueue and dequeue ops
        if len(queue_ver) >= n:
            ver_ave = np.mean(queue_ver, axis=0)

            if args.opt == '2d_sparse':
                img_draw = cv_draw_landmark(queue_frame[n_pre],
                                            ver_ave)  # since we use padding
            elif args.opt == '2d_dense':
                img_draw = cv_draw_landmark(queue_frame[n_pre],
                                            ver_ave,
                                            size=1)
            elif args.opt == '3d':
                img_draw = render(queue_frame[n_pre], [ver_ave],
                                  tddfa.bfm.tri,
                                  alpha=0.7)
            else:
                raise ValueError(f'Unknown opt {args.opt}')

            writer.append_data(img_draw[:, :, ::-1])  # BGR->RGB

            queue_ver.popleft()
            queue_frame.popleft()

    # we will lost the last n_next frames, still padding
    for _ in range(n_next):
        queue_ver.append(ver.copy())
        queue_frame.append(frame_bgr.copy())  # the last frame

        ver_ave = np.mean(queue_ver, axis=0)

        if args.opt == '2d_sparse':
            img_draw = cv_draw_landmark(queue_frame[n_pre],
                                        ver_ave)  # since we use padding
        elif args.opt == '2d_dense':
            img_draw = cv_draw_landmark(queue_frame[n_pre], ver_ave, size=1)
        elif args.opt == '3d':
            img_draw = render(queue_frame[n_pre], [ver_ave],
                              tddfa.bfm.tri,
                              alpha=0.7)
        else:
            raise ValueError(f'Unknown opt {args.opt}')

        writer.append_data(img_draw[..., ::-1])  # BGR->RGB

        queue_ver.popleft()
        queue_frame.popleft()

    writer.close()
    print(f'Dump to {video_wfp}')
Пример #40
0
def main(args):
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)

    # Init FaceBoxes and TDDFA, recommend using onnx flag
    if args.onnx:
        import os
        os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
        os.environ['OMP_NUM_THREADS'] = '4'

        from FaceBoxes.FaceBoxes_ONNX import FaceBoxes_ONNX
        from TDDFA_ONNX import TDDFA_ONNX

        face_boxes = FaceBoxes_ONNX()
        tddfa = TDDFA_ONNX(**cfg)
    else:
        gpu_mode = args.mode == 'gpu'
        tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)
        face_boxes = FaceBoxes()

    # Given a still image path and load to BGR channel
    img = cv2.imread(args.img_fp)

    # Detect faces, get 3DMM params and roi boxes
    boxes = face_boxes(img)
    n = len(boxes)
    if n == 0:
        print(f'No face detected, exit')
        sys.exit(-1)
    print(f'Detect {n} faces')

    param_lst, roi_box_lst = tddfa(img, boxes)

    # Visualization and serialization
    dense_flag = args.opt in ('2d_dense', '3d', 'depth', 'pncc', 'uv_tex',
                              'ply', 'obj')
    old_suffix = get_suffix(args.img_fp)
    new_suffix = f'.{args.opt}' if args.opt in ('ply', 'obj') else '.jpg'

    wfp = f'examples/results/{args.img_fp.split("/")[-1].replace(old_suffix, "")}_{args.opt}' + new_suffix

    ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)

    print(ver_lst[0].shape)

    print(tddfa.bfm.u.shape)

    lm68 = np.reshape(
        np.reshape(ver_lst[0].T, (-1, 1))[tddfa.bfm.keypoints], (-1, 3))
    print(lm68.shape)

    for i in range(lm68.shape[0]):
        lm68[i, 1] = img.shape[0] - lm68[i, 1]

    for i in range(ver_lst[0].shape[1]):
        ver_lst[0][1, i] = img.shape[0] - ver_lst[0][1, i]

    useful_tri = np.copy(tddfa.tri)

    for i in range(useful_tri.shape[0]):
        tmp = useful_tri[i, 2]
        useful_tri[i, 2] = useful_tri[i, 0]
        useful_tri[i, 0] = tmp

    useful_tri = useful_tri + 1

    np.save("asd_lm.npy", lm68)
    np.save("asd_v.npy", ver_lst[0].T)
    np.save("asd_f.npy", useful_tri)

    if args.opt == '2d_sparse':
        draw_landmarks(img,
                       ver_lst,
                       show_flag=args.show_flag,
                       dense_flag=dense_flag,
                       wfp=wfp)
    elif args.opt == '2d_dense':
        draw_landmarks(img,
                       ver_lst,
                       show_flag=args.show_flag,
                       dense_flag=dense_flag,
                       wfp=wfp)
    elif args.opt == '3d':
        render(img,
               ver_lst,
               tddfa.tri,
               alpha=0.6,
               show_flag=args.show_flag,
               wfp=wfp)
    elif args.opt == 'depth':
        # if `with_bf_flag` is False, the background is black
        depth(img,
              ver_lst,
              tddfa.tri,
              show_flag=args.show_flag,
              wfp=wfp,
              with_bg_flag=True)
    elif args.opt == 'pncc':
        pncc(img,
             ver_lst,
             tddfa.tri,
             show_flag=args.show_flag,
             wfp=wfp,
             with_bg_flag=True)
    elif args.opt == 'uv_tex':
        uv_tex(img, ver_lst, tddfa.tri, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'pose':
        viz_pose(img, param_lst, ver_lst, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'ply':
        ser_to_ply(ver_lst, tddfa.tri, height=img.shape[0], wfp=wfp)
    elif args.opt == 'obj':
        ser_to_obj(img, ver_lst, tddfa.tri, height=img.shape[0], wfp=wfp)
    else:
        raise ValueError(f'Unknown opt {args.opt}')
Пример #41
0
def main(args):
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)

    # Init FaceBoxes and TDDFA, recommend using onnx flag
    if args.onnx:
        import os
        os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
        os.environ['OMP_NUM_THREADS'] = '4'

        from FaceBoxes.FaceBoxes_ONNX import FaceBoxes_ONNX
        from TDDFA_ONNX import TDDFA_ONNX

        face_boxes = FaceBoxes_ONNX()
        tddfa = TDDFA_ONNX(**cfg)
    else:
        gpu_mode = args.mode == 'gpu'
        tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)
        face_boxes = FaceBoxes()

    # Given a camera
    # before run this line, make sure you have installed `imageio-ffmpeg`
    reader = imageio.get_reader("<video0>")

    # the simple implementation of average smoothing by looking ahead by n_next frames
    # assert the frames of the video >= n
    n_pre, n_next = args.n_pre, args.n_next
    n = n_pre + n_next + 1
    queue_ver = deque()
    queue_frame = deque()

    # run
    dense_flag = args.opt in ('2d_dense', '3d')
    pre_ver = None
    for i, frame in tqdm(enumerate(reader)):
        frame_bgr = frame[..., ::-1]  # RGB->BGR

        if i == 0:
            # the first frame, detect face, here we only use the first face, you can change depending on your need
            boxes = face_boxes(frame_bgr)
            boxes = [boxes[0]]
            param_lst, roi_box_lst = tddfa(frame_bgr, boxes)
            ver = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)[0]

            # refine
            param_lst, roi_box_lst = tddfa(frame_bgr, [ver], crop_policy='landmark')
            ver = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)[0]

            # padding queue
            for _ in range(n_pre):
                queue_ver.append(ver.copy())
            queue_ver.append(ver.copy())

            for _ in range(n_pre):
                queue_frame.append(frame_bgr.copy())
            queue_frame.append(frame_bgr.copy())
        else:
            param_lst, roi_box_lst = tddfa(frame_bgr, [pre_ver], crop_policy='landmark')

            roi_box = roi_box_lst[0]
            # todo: add confidence threshold to judge the tracking is failed
            if abs(roi_box[2] - roi_box[0]) * abs(roi_box[3] - roi_box[1]) < 2020:
                boxes = face_boxes(frame_bgr)
                boxes = [boxes[0]]
                param_lst, roi_box_lst = tddfa(frame_bgr, boxes)

            ver = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)[0]

            queue_ver.append(ver.copy())
            queue_frame.append(frame_bgr.copy())

        pre_ver = ver  # for tracking

        # smoothing: enqueue and dequeue ops
        if len(queue_ver) >= n:
            ver_ave = np.mean(queue_ver, axis=0)

            if args.opt == '2d_sparse':
                img_draw = cv_draw_landmark(queue_frame[n_pre], ver_ave)  # since we use padding
            elif args.opt == '2d_dense':
                img_draw = cv_draw_landmark(queue_frame[n_pre], ver_ave, size=1)
            elif args.opt == '3d':
                img_draw = render(queue_frame[n_pre], [ver_ave], tddfa.tri, alpha=0.7)
            else:
                raise ValueError(f'Unknown opt {args.opt}')

            cv2.imshow('image', img_draw)
            k = cv2.waitKey(20)
            if (k & 0xff == ord('q')):
                break

            queue_ver.popleft()
            queue_frame.popleft()
Пример #42
0
def main(args):
    cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)

    # Init FaceBoxes and TDDFA, recommend using onnx flag
    if args.onnx:
        import os
        os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
        os.environ['OMP_NUM_THREADS'] = '4'

        from FaceBoxes.FaceBoxes_ONNX import FaceBoxes_ONNX
        from TDDFA_ONNX import TDDFA_ONNX

        face_boxes = FaceBoxes_ONNX()
        tddfa = TDDFA_ONNX(**cfg)
    else:
        gpu_mode = args.mode == 'gpu'
        tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)
        face_boxes = FaceBoxes()

    # Given a still image path and load to BGR channel
    img = cv2.imread(args.img_fp)

    # Detect faces, get 3DMM params and roi boxes
    boxes = face_boxes(img)
    n = len(boxes)
    if n == 0:
        print('No face detected, exit')
        sys.exit(-1)
    print(f'Detect {n} faces')

    param_lst, roi_box_lst = tddfa(img, boxes)

    # Visualization and serialization
    dense_flag = args.opt in ('2d_dense', '3d', 'depth', 'pncc', 'uv_tex',
                              'ply', 'obj')
    old_suffix = get_suffix(args.img_fp)
    new_suffix = f'.{args.opt}' if args.opt in ('ply', 'obj') else '.jpg'

    wfp = f'{args.img_fp.split("/")[-1].replace(old_suffix, "")}_{args.opt}' +\
        new_suffix
    wfp = base_path / 'examples' / 'results' / wfp

    ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag=dense_flag)

    if args.opt == '2d_sparse':
        draw_landmarks(img,
                       ver_lst,
                       show_flag=args.show_flag,
                       dense_flag=dense_flag,
                       wfp=wfp)
    elif args.opt == '2d_dense':
        draw_landmarks(img,
                       ver_lst,
                       show_flag=args.show_flag,
                       dense_flag=dense_flag,
                       wfp=wfp)
    elif args.opt == '3d':
        render(img,
               ver_lst,
               tddfa.tri,
               alpha=0.6,
               show_flag=args.show_flag,
               wfp=wfp)
    elif args.opt == 'depth':
        # if `with_bf_flag` is False, the background is black
        depth(img,
              ver_lst,
              tddfa.tri,
              show_flag=args.show_flag,
              wfp=wfp,
              with_bg_flag=True)
    elif args.opt == 'pncc':
        pncc(img,
             ver_lst,
             tddfa.tri,
             show_flag=args.show_flag,
             wfp=wfp,
             with_bg_flag=True)
    elif args.opt == 'uv_tex':
        uv_tex(img, ver_lst, tddfa.tri, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'pose':
        viz_pose(img, param_lst, ver_lst, show_flag=args.show_flag, wfp=wfp)
    elif args.opt == 'ply':
        ser_to_ply(ver_lst, tddfa.tri, height=img.shape[0], wfp=wfp)
    elif args.opt == 'obj':
        ser_to_obj(img, ver_lst, tddfa.tri, height=img.shape[0], wfp=wfp)
    else:
        raise ValueError(f'Unknown opt {args.opt}')