def do_search_api(): input_args = reqparse.RequestParser(). \ add_argument("Table", type=str). \ add_argument("Num", type=int, default=1). \ add_argument("Caption", type=str). \ parse_args() captions = input_args['Caption'] print(captions) table_name = input_args['Table'] top_k = input_args['Num'] if not table_name: table_name = DEFAULT_TABLE print(table_name) if not captions: return "no captions", 400 if captions: # filename = secure_filename(file.filename) # file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) # file.save(file_path) res_id, res_distance = do_search(table_name, captions, top_k, model, args) if isinstance(res_id, str): return res_id # res_img = [request.url_root + "data/" + x for x in res_id] # res = dict(zip(res_img, res_distance)) # res = sorted(res.items(), key=lambda item: item[1]) # return jsonify(res), 200 return "not found", 400
def do_search_api(): args = reqparse.RequestParser(). \ add_argument("Molecular", type=str). \ add_argument("Type", type=str, default='similarity'). \ add_argument("Cid", type=int). \ parse_args() molecular_name = args['Molecular'] search_type = args['Type'] cid_num = args['Cid'] if search_type == 'similarity': table_name = SIM_TABLE elif search_type == 'substructure': table_name = SUB_TABLE elif search_type == 'superstructure': table_name = SUPER_TABLE top_k = NUM if cid_num: from pubchempy import get_compounds, Compound comp = Compound.from_cid(cid_num) molecular_name = comp.isomeric_smiles if not molecular_name: return "no molecular" if molecular_name: try: res_smi = do_search(table_name, molecular_name, top_k) except: return "There has no results, please input the correct molecular and ensure the table has data." re = {} re["Smiles"] = res_smi return jsonify(re), 200 return "not found", 400
def do_search_api(): args = reqparse.RequestParser(). \ add_argument("Table", type=str). \ add_argument("Num", type=int, default=1). \ parse_args() table_name = args['Table'] if not table_name: table_name = DEFAULT_TABLE top_k = args['Num'] file = request.files.get('file', "") if not file: return "no file data", 400 if not file.name: return "need file name", 400 if file: filename = secure_filename(file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) res_id, res_distance = do_search(table_name, file_path, top_k, model, graph, sess) if isinstance(res_id, str): return res_id res_img = [request.url_root + "data/" + x for x in res_id] res = dict(zip(res_img, res_distance)) res = sorted(res.items(), key=lambda item: item[1]) print(jsonify(res)) return jsonify(res), 200 return "not found", 400
def do_search_images_api(): args = reqparse.RequestParser(). \ add_argument('Id', type=str). \ add_argument('Table', type=str). \ add_argument('Image', type=str). \ add_argument('FileId', type=str). \ add_argument('FileImage', type=str). \ parse_args() file_id = request.files.get('FileId', "") file_image = request.files.get('FileImage', "") table_name = args['Table'] if file_id: ids = str(file_id.read().decode("utf-8")).strip().split(",") ids = ids[:-1] else: ids = args['Id'].split(",") if file_image: image = str(file_image.read().decode("utf-8")).strip().split(",") image = image[:-1] else: image = args['Image'].split(",") try: index_client, conn, cursor = init_conn() result, distance = do_search(index_client, conn, cursor, img_to_vec, image, table_name) print("----------------search_results:", result, distance) # Python 字典类型转换为 JSON 对象 result_dic = {"code": 0, "msg": "success"} data = [] for i in range(len(ids)): id_dis = [] for j in range(len(result[i])): id_sim = {"id": result[i][j], "similarity": distance[i][j]} id_dis.append(id_sim) re_sim = {"id": ids[i], "similarImages": id_dis} data.append(re_sim) result_dic["data"] = data # with open("results_0630.txt","w") as f: # f.write(str(ids).replace('[','').replace(']','').replace('\'','').replace('‘','')+'\n') # f.write("\n") # for i in result: # f.write(str(i).replace('[','').replace(']','').replace('\'','').replace('‘','')+'\n') # return "{0},{1}".format(ids, result), 200 return result_dic, 200 except Exception as e: write_log(e, 1) return "Error with {}".format(e), 400
def do_search_images_api(request: Request, search_id: list, table_name: str=None): try: index_client, conn, cursor = init_conn() host = request.headers['host'] img_list = get_img_list() list_id = do_search(index_client, conn, cursor, img_list, search_id, table_name) # print("--------", list_id) info = get_list_info(conn, cursor, table_name, host, list_id) return info, 200 except Exception as e: logging.error(e) return "Error with {}".format(e), 400
async def do_search_images_api(request: Request, Text: str, Image: UploadFile = File(...), table_name: str=None): try: index_client, conn, cursor = init_conn() host = request.headers['host'] content = await Image.read() with open ("./test/test.png" ,'wb') as f : f.write(content) Image ="./test/test.png" img_list = get_img_list() list_id = do_search(index_client, conn, cursor ,Text, Image,table_name,img_list,host) print("--------", list_id) return list_id, 200 except Exception as e: logging.error(e) print(traceback.format_exc())
def do_search_api(): args = reqparse.RequestParser(). \ add_argument("Table", type=str). \ add_argument("Num", type=int, default=1). \ add_argument("Molecular", type=str). \ parse_args() table_name = args['Table'] if not table_name: table_name = DEFAULT_TABLE top_k = args['Num'] molecular_name = args['Molecular'] if not molecular_name: return "no molecular" if molecular_name: try: shutil.rmtree(UPLOAD_PATH) os.mkdir(UPLOAD_PATH) except: print("cannot remove:", UPLOAD_PATH) try: res_smi, res_distance, ids = do_search(table_name, molecular_name, top_k) except: return "There has no results, please input the correct molecular and ensure the table has data." res_mol = [] for i in range(len(res_smi)): mol = Chem.MolFromSmiles(res_smi[i]) res_mol.append(mol) print("res_mol:", len(res_mol)) re = {} for i in range(len(res_smi)): times = int(time.time()) sub_res_mol = [res_mol[i]] sub_img = Draw.MolsToGridImage(sub_res_mol, molsPerRow=1, subImgSize=(500, 500)) sub_img.save(UPLOAD_PATH + "/similarities_results_" + str(ids[i]) + "_" + str(times) + ".png") res_img = request.url_root + "data/similarities_results_" + str( ids[i]) + "_" + str(times) + ".png" re[res_img] = [res_smi[i], res_distance[i]] # img = Draw.MolsToGridImage(res_mol, molsPerRow=1, subImgSize=(500, 500),legends=["%s - %s" % (res_smi[x] , str(res_distance[x])) for x in range(len(res_mol))]) return jsonify(re), 200 return "not found", 400
def do_search_api(): args = reqparse.RequestParser(). \ add_argument("Table", type=str). \ add_argument("Num", type=int, default=1). \ parse_args() table_name = args['Table'] if not table_name: table_name = DEFAULT_TABLE top_k = args['Num'] file = request.files.get('file', "") if not file: return "no file data", 400 if not file.name: return "need file name", 400 if file: filename = secure_filename(file.filename) img_path = app.config['UPLOAD_FOLDER']+'/'+filename.split('.')[0] if not os.path.exists(img_path): os.mkdir(img_path) file_path = os.path.join(img_path, filename) file.save(file_path) res_id,res_distance = do_search(image_encoder,table_name, img_path, top_k) # print(res_id,res_distance) # if isinstance(res_id, str): # return res_id res ={} for img, dis in zip(res_id,res_distance): # print("[[[[[[[[[[[[[[", img, dis) key_img = request.url_root +"data/" + img if key_img not in res.keys() or res[key_img] > dis: res[key_img] = dis #print("dic res:", res) # res = dict(zip(res_img,res_distance)) #res = [list(g)[0] for k, g in groupby(sorted(res), key=itemgetter(0))] # print(",,,,,,,",res) res = sorted(res.items(),key=lambda item:item[1]) # myslice = slice(top_k) # res=res[myslice] return jsonify(res), 200 return "not found", 400
def do_search_api(): file_img = request.files.get('img', "") file_video = request.files.get('video', None) file_audio = request.files.get('audio', None) ids = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now()) status = {'status': 'faile', 'message': 'no file data'} if file_video: filename = secure_filename(file_video.filename) file_path = os.path.join(app.config['DATA_FOLDER'], filename) file_video.save(file_path) video = VideoFileClip(file_path) audio = video.audio voc_path = os.path.join(app.config['DATA_FOLDER'], ids[:-1] + '.wav') audio.write_audiofile(voc_path) elif file_audio: voc_path = os.path.join(app.config['DATA_FOLDER'], ids[:-1] + '.wav') file_audio.save(voc_path) else: return jsonify(status), 200 if file_img: img_path = os.path.join(app.config['DATA_FOLDER'], ids + '.png') file_img.save(img_path) try: status = do_search(img_path, voc_path) status[1] = request.url_root + "data/" + str(status[1]) + '.png' except: status = { 'status': 'faile', 'message': 'please confirm only one face in camera' } return jsonify(status), 200 finally: os.remove(img_path) os.remove(voc_path) return "{}".format(status), 200 else: return jsonify(status), 200
if not captions: return "no captions", 400 if captions: # filename = secure_filename(file.filename) # file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) # file.save(file_path) res_id, res_distance = do_search(table_name, captions, top_k, model, args) if isinstance(res_id, str): return res_id # res_img = [request.url_root + "data/" + x for x in res_id] # res = dict(zip(res_img, res_distance)) # res = sorted(res.items(), key=lambda item: item[1]) # return jsonify(res), 200 return "not found", 400 if __name__ == "__main__": global args global test_loader global test_transform args = config() test_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) test_loader = data_config(args.image_dir, args.anno_dir, 64, 'test', args.max_length, test_transform) load_model() # do_train('test02', test_loader, model, args) captions = 'The man is wearing a blue and white striped tank top and green pants. He has pink headphones around his neck.' do_search('test02', captions, 10, model, args) app.run(host="192.168.1.85", port='5001')