Spaces:
Sleeping
Sleeping
import json | |
import requests | |
import gradio as gr | |
import typesense | |
from urllib.parse import quote | |
import os | |
def getWordVec(content): | |
content=quote(content,'utf-8') | |
#print(content) | |
xurl=os.getenv("emburl") | |
print(xurl) | |
url=xurl +content | |
#print(url) | |
response = requests.get(url) | |
jsonar=json.loads(response.text).get("embed") | |
#print(len(jsonar)) | |
return jsonar | |
typesenseserver=os.getenv("typesenseserver") | |
typesenseport=os.getenv("typesenseport") | |
typesensekey=os.getenv("typesensekey") | |
typesensecolname=os.getenv("typesensecolname") | |
confignode={} | |
confignode['host']=typesenseserver | |
confignode['port']=typesenseport | |
confignode['protocol']='http' | |
nodes=[] | |
nodes.append(confignode) | |
nodeconfig={} | |
nodeconfig["nodes"]=nodes | |
nodeconfig["api_key"]=typesensekey | |
print(nodeconfig) | |
client = typesense.Client(nodeconfig) | |
def queryimgage(text): | |
html="<table border='1'>\ | |
<tr>\ | |
<th>img</th>\ | |
<th>score</th>\ | |
</tr>" | |
info=getWordVec(text) | |
search_requests = { | |
'searches': [ | |
{ | |
'collection': typesensecolname, | |
'q' : '*', | |
'per_page': 20, | |
'exclude_fields' : 'my_vector', | |
'vector_query': 'my_vector:(['+",".join(str(x) for x in info )+'], k:1000)' | |
} | |
] | |
} | |
common_search_params = {} | |
res=client.multi_search.perform(search_requests, common_search_params) | |
result=res['results'][0]['hits'] | |
for resultinfo in result: | |
documents=resultinfo['document'] | |
score=(2-resultinfo['vector_distance'])/2 | |
html=html +"<tr>\ | |
<td><img src='"+documents['imageurl']+"' width=640 height=600></td>\ | |
<td>"+ str(score)+"</td>" | |
html=html+"</table>" | |
return html | |
def getNumtip(): | |
num=client.collections[typesensecolname].retrieve()["num_documents"] | |
numtip="图片数:" + str(num) | |
return numtip | |
demo = gr.Interface( | |
fn=queryimgage, | |
inputs=gr.Textbox(placeholder="请输入文本"), | |
outputs=[ "html"], | |
article=getNumtip() | |
) | |
demo.launch() |