Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from fastapi.responses import StreamingResponse, HTMLResponse
|
3 |
+
import json
|
4 |
+
from es_gpt import ESGPT
|
5 |
+
import asyncio
|
6 |
+
|
7 |
+
# Create an instance of the ESGPT class
|
8 |
+
es = ESGPT(index_name="papers")
|
9 |
+
|
10 |
+
# Create a FastAPI app
|
11 |
+
app = FastAPI()
|
12 |
+
|
13 |
+
# Define the search route
|
14 |
+
|
15 |
+
|
16 |
+
@app.get("/", response_class=HTMLResponse)
|
17 |
+
async def read_index():
|
18 |
+
with open("index.html", "r") as file:
|
19 |
+
html = file.read()
|
20 |
+
return html
|
21 |
+
|
22 |
+
|
23 |
+
@app.get("/search")
|
24 |
+
async def search(q: str):
|
25 |
+
# Perform a search for the query
|
26 |
+
results = es.search(q)
|
27 |
+
print(results)
|
28 |
+
|
29 |
+
# Stream the search results to the client
|
30 |
+
async def stream_response():
|
31 |
+
for hit in results:
|
32 |
+
# sleep(0.1)
|
33 |
+
await asyncio.sleep(0.1)
|
34 |
+
yield "data: " + json.dumps(hit) + "\n\n"
|
35 |
+
yield "[DONE]"
|
36 |
+
|
37 |
+
return StreamingResponse(stream_response(), media_type="text/event-stream")
|
38 |
+
|
39 |
+
# Define the summary route
|
40 |
+
|
41 |
+
|
42 |
+
@app.get("/summary")
|
43 |
+
async def summary(q: str):
|
44 |
+
# Perform a search for the query
|
45 |
+
results = es.search(q)
|
46 |
+
|
47 |
+
# Generate summaries of the search results
|
48 |
+
resp = es.summarize(q, results)
|
49 |
+
|
50 |
+
if resp.status_code != 200:
|
51 |
+
raise HTTPException(resp.status_code, resp.text)
|
52 |
+
|
53 |
+
return StreamingResponse(resp.iter_content(1),
|
54 |
+
media_type="text/event-stream")
|