def query_user_info(userslug, run_query=True): query = (""" { user(input: {selector: {slug: "%s"}}) { result { _id slug karma htmlBio website location profile displayName username postCount commentCount } } } """ % userslug) if not run_query: query_url = config.GRAPHQL_URL.replace( "graphql", "graphiql") + "?query=" + quote(query) return query + ('''\n<a href="%s">Run this query</a>\n\n''' % query_url) request = util.send_query(query) return request.json()['data']['user']['result']
def get_content_for_tag(tagslug, run_query=True): query = (""" { tag( input: { selector: { slug: "%s" } } ) { result { description { html } } } } """ % tagslug) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) try: return request.json()['data']['tag']['result'] except TypeError: return {}
def recent_comments_query(run_query=True): query = (""" { comments(input: { terms: { view: "recentComments" limit: 10 } }) { results { _id post { _id title slug } user { _id slug username displayName } htmlBody postId pageUrl } } } """) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) return request.json()['data']['comments']['results']
def users_list_query(sort_by="karma", run_query=True): sort_line = "" if sort_by == "postCount": sort_line = 'sort: {postCount: -1}' elif sort_by == "commentCount": sort_line = 'sort: {commentCount: -1}' else: sort_line = 'sort: {karma: -1}' query = (""" { users(input: { terms: { view: "LWUsersAdmin" limit: 500 %s } }) { results { _id slug karma postCount commentCount } } } """ % sort_line) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) return request.json()['data']['users']['results']
def get_chapter(chapterid, run_query=True): query = (""" { chapter( input: { selector: { _id: "%s" } } ) { result { posts { title pageUrl } } } } """ % chapterid) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) return util.safe_get(request.json(), ['data', 'chapter', 'result'])
def main(): args = parse_args() if args.random_seed is not None: # fixed random seeds for reproducibility np.random.seed(args.random_seed) torch.random.manual_seed(args.random_seed) # infer target label from image input_img = load_image(args.input_img, size=64) labels, confidences = send_query(input_img) target_idx = np.argmax(confidences) target_class = labels[target_idx] # ask user if he wants to continue print(f'Inferred label: {target_class}, confidence of {np.round(confidences[target_idx], 3)}') if not query_yes_no('Continue ?'): print('Please choose an input image which the API classifies as your target class. ') sys.exit(0) # generate adversarial image else: if not args.color: target_img = image_to_grayscale(input_img) else: target_img = input_img print('Generating adversarial...') adversarial, conf, num_queries, conv_images, cppn = generate_adversarial(target_class=target_class, target_image=target_img, color=args.color, target_conf=args.target_conf, max_queries=args.max_queries, init=args.init) if conf < args.target_conf: print(f'Failed to generate an adversarial image after {args.max_queries} queries.') # write_to_log('log.tsv', f'{target_class}\t{conf}\t{num_queries}\t{args.color}\t{args.init}') sys.exit(0) print(f'Found an adversarial image with > {args.target_conf} API confidence after {num_queries} queries.') output_dir = Path(args.output_dir) print(f'\tSaving results in: {output_dir}/') # save adversarial image adversarial_fname = str(output_dir / f'adversarial_{clean_filename(target_class)}_{conf}') save_image(adversarial_fname + '.png', adversarial) if args.high_res: cppn.set_img_size(2000) adversarial_high_res = cppn.render_image() save_image(adversarial_fname + '_HD.png', adversarial_high_res) # save convergence gif if not args.no_gif: conv_gif_fname = str(output_dir / f'convergence_{clean_filename(target_class)}_{conf}.gif') save_gif_from_images(conv_gif_fname, conv_images) # write_to_log('log.tsv', f'{target_class}\t{conf}\t{num_queries}\t{args.color}\t{args.init}') print('Finished.')
async def on_receive(self, websocket, data): # If the id tag is send with other data, we assume the client wants to set his ID if 'id' in data.keys(): print('Client with ID', data['id'], 'connected') self.id = data['id'] if 'image' in data.keys(): print('Recived an Image') # Strip die data\png;base64, from the image data stream matcher = re.match( r"data:([\w\/\+]+);(charset=[\w-]+|base64).*,([a-zA-Z0-9+/]+={0,2})", data['image']) raw_data = matcher.group(3) # Save file with the id of the client with open('server/image/' + self.id, "wb") as f: f.write(base64.b64decode(raw_data)) # Reload Image as Byte object. It is also croped to size img = load_img_to_bytes('server/image/' + self.id) img = io.imread(img) # Get Labels for the Image from the API labels, confs = send_query(img) # Send Labels to the the Client await websocket.send_json({ 'labels': labels.tolist(), 'confs': confs.tolist() }) if { 'start', 'target_class', 'target_conf', 'init', 'max_queries', 'rgb' } <= data.keys(): if data['start']: print('Start fooling with', data['target_class'], data['target_conf'], data['max_queries'], data['init'], data['rgb'], 'for client', self.id) img = load_image('server/image/' + self.id, size=64) if not data['rgb']: img = image_to_grayscale(img) thread = Thread(target=generate_adversarial, kwargs=dict( target_class=data['target_class'], target_image=img, target_conf=float(data['target_conf']), init=data['init'], max_queries=int(data['max_queries']), color=data['rgb'], websocket=websocket, client_id=self.id)) thread.start()
def get_sequence(sequenceid, run_query=True): query = (""" { sequence( input: { selector: { _id: "%s" } } ) { result { title user { _id username } userId createdAt canonicalCollection { createdAt userId title slug gridImageId firstPageLink version _id schemaVersion } contents { html _id } chapters { createdAt title subtitle number sequenceId _id } } } } """ % sequenceid) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) return util.safe_get(request.json(), ['data', 'sequence', 'result'])
def get_comments_for_user(username, run_query=True): userid = util.userslug_to_userid(username, run_query=True) query = (""" { comments(input: { terms: { view: "userComments", userId: "%s", limit: 50, } }) { results { _id post { title slug } user { username slug displayName } userId postId postedAt pageUrl htmlBody baseScore voteCount } } } """ % userid) if not run_query: return util.userslug_to_userid( username, run_query=False) + "\n\n" + query + ( '''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) result = [] for comment in request.json()['data']['comments']['results']: result.append(comment) return result
def posts_list_query(view="new", offset=0, before="", after="", run_query=True): query = (""" { posts(input: { terms: { view: "%s" limit: 50 meta: null # this seems to get both meta and non-meta posts %s %s %s } }) { results { _id title slug pageUrl postedAt baseScore voteCount commentsCount meta question url user { username slug displayName } } } } """ % ( view, "offset: " + str(offset) if offset > 0 else "", ('before: "%s"' % before) if before else "", ('after: "%s"' % after) if after else "" ) ) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) return request.json()['data']['posts']['results']
def query_question_answers(postid, run_query=True): query = (""" { comments(input: { terms: { view: "questionAnswers", postId: "%s", } }) { results { _id user { _id username displayName slug bio } userId author parentCommentId pageUrl htmlBody baseScore voteCount postedAt answer } } } """ % postid) if not run_query: query_url = config.GRAPHQL_URL.replace( "graphql", "graphiql") + "?query=" + quote(query) return query + ('''\n<a href="%s">Run this query</a>\n\n''' % query_url) request = util.send_query(query) result = [] for answer in request.json()['data']['comments']['results']: result.append(answer) return result
def get_comments_for_post(postid, view="postCommentsTop", run_query=True): query = (""" { comments(input: { terms: { view: "%s", postId: "%s", } }) { results { _id user { _id username displayName slug bio } userId author parentCommentId pageUrl htmlBody baseScore voteCount postedAt } } } """ % (view, postid)) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) result = [] for comment in request.json()['data']['comments']['results']: result.append(comment) return result
def get_posts_for_user(username, run_query=True): userid = util.userslug_to_userid(username, run_query=True) query = (""" { posts(input: { terms: { view: "userPosts" userId: "%s" limit: 50 meta: null # this seems to get both meta and non-meta posts } }) { results { _id title pageUrl postedAt htmlBody voteCount baseScore slug } } } """ % userid) if not run_query: return util.userslug_to_userid( username, run_query=False) + "\n\n" + query + ( '''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) result = [] for post in request.json()['data']['posts']['results']: result.append(post) return result
def get_content_for_post(postid, run_query=True): query = (""" { post( input: { selector: { _id: "%s" } } ) { result { _id postedAt url canonicalSource title slug commentCount htmlBody baseScore voteCount pageUrl legacyId question tableOfContents user { username displayName slug bio } coauthors { _id username displayName slug } } } } """ % postid) if not run_query: return query + ('''\n<a href="%s">Run this query</a>\n\n''' % (config.GRAPHQL_URL.replace("graphql", "graphiql") + "?query=" + quote(query))) request = util.send_query(query) try: return request.json()['data']['post']['result'] except TypeError: return { 'title': '', 'slug': '', 'baseScore': 0, 'voteCount': 0, 'pageUrl': '', 'url': '', 'htmlBody': '', 'postedAt': '', 'commentCount': 0, 'legacyId': None, 'user': { 'slug': '', 'username': '' }, 'question': False, 'tableOfContents': { 'headingsCount': 0, 'html': "", 'sections': [] } }