cheeku2 commited on
Commit
03edc33
1 Parent(s): 01697df

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +35 -35
app/main.py CHANGED
@@ -1,14 +1,12 @@
1
  import os
2
- import traceback
3
  import logging
4
- import pathlib
5
  import time
6
  import re
7
- from typing import List
8
- from fastapi import FastAPI, Request, Depends, HTTPException
9
  from fastapi.middleware import Middleware
10
  from fastapi.middleware.cors import CORSMiddleware
11
- from fastapi.responses import StreamingResponse
12
  from .rag import ChatPDF
13
 
14
  middleware = [
@@ -23,26 +21,34 @@ middleware = [
23
  app = FastAPI(middleware=middleware)
24
 
25
  files_dir = os.path.expanduser("~/wtp_be_files/")
26
- os.makedirs(files_dir)
27
  session_assistant = ChatPDF()
28
 
29
  logging.basicConfig(level=logging.INFO)
30
  logger = logging.getLogger(__name__)
31
  isBusy = False
32
 
 
 
 
 
 
 
 
 
 
33
  def astreamer(generator):
 
34
  t0 = time.time()
35
  for i in generator:
36
- logger.info(f"Chunk being yielded (time {int((time.time()-t0)*1000)}ms)")
37
  yield i
38
- logger.info(f"Over (time {int((time.time()-t0)*1000)}ms)")
 
39
 
40
 
41
  @app.get("/query")
42
  async def process_input(text: str):
43
  global isBusy
44
- if isBusy:
45
- raise HTTPException(status_code=503, detail="Server is busy")
46
  isBusy = True
47
  generator = None
48
  if text and len(text.strip()) > 0:
@@ -51,49 +57,43 @@ async def process_input(text: str):
51
  streaming_response = session_assistant.ask(text)
52
  generator = streaming_response.response_gen
53
  else:
54
- message = "Please add a PDF document first."
55
  generator = re.split(r'(\s)', message)
56
  else:
57
- message = "The provided query is empty."
58
  generator = re.split(r'(\s)', message)
59
- isBusy = False
60
  return StreamingResponse(astreamer(generator), media_type='text/event-stream')
61
 
62
- async def parse_body(request: Request):
63
- data: bytes = await request.body()
64
- return data
65
 
66
  @app.post("/upload")
67
- def upload(filename: str, data: bytes = Depends(parse_body)):
68
  global isBusy
69
- if isBusy:
70
- raise HTTPException(status_code=503, detail="Server is busy")
71
  isBusy = True
72
- session_assistant.clear()
73
- if data:
74
- try:
75
- print("Filename: " + filename)
76
- path = f"{files_dir}/{filename}"
77
- with open(path, "wb") as f:
78
- f.write(data)
79
- session_assistant.ingest(files_dir)
80
- pathlib.Path(path).unlink()
81
- except Exception as e:
82
- logging.error(traceback.format_exc())
83
-
84
- message = "Files inserted successfully."
 
85
  generator = re.split(r'(\s)', message)
86
- isBusy = False
87
  return StreamingResponse(astreamer(generator), media_type='text/event-stream')
88
 
89
 
90
  @app.get("/clear")
91
  def clear():
92
  global isBusy
 
93
  session_assistant.clear()
94
- message = "All files have been cleared. The first query may take a little longer."
95
  generator = re.split(r'(\s)', message)
96
- isBusy = False
97
  return StreamingResponse(astreamer(generator), media_type='text/event-stream')
98
 
99
 
 
1
  import os
 
2
  import logging
3
+ import shutil
4
  import time
5
  import re
6
+ from fastapi import FastAPI, Request, UploadFile
 
7
  from fastapi.middleware import Middleware
8
  from fastapi.middleware.cors import CORSMiddleware
9
+ from fastapi.responses import PlainTextResponse, StreamingResponse
10
  from .rag import ChatPDF
11
 
12
  middleware = [
 
21
  app = FastAPI(middleware=middleware)
22
 
23
  files_dir = os.path.expanduser("~/wtp_be_files/")
 
24
  session_assistant = ChatPDF()
25
 
26
  logging.basicConfig(level=logging.INFO)
27
  logger = logging.getLogger(__name__)
28
  isBusy = False
29
 
30
+ @app.middleware("http")
31
+ async def resolve_availability(request: Request, call_next):
32
+ global isBusy
33
+ if isBusy:
34
+ return PlainTextResponse("Server is busy", status_code=503)
35
+ response = await call_next(request)
36
+ return response
37
+
38
+
39
  def astreamer(generator):
40
+ global isBusy
41
  t0 = time.time()
42
  for i in generator:
43
+ logger.info(f"Chunk being yielded (time {int((time.time()-t0)*1000)}ms) - {i}")
44
  yield i
45
+ logger.info(f"X-Process-Time: {int((time.time()-t0)*1000)}ms")
46
+ isBusy = False
47
 
48
 
49
  @app.get("/query")
50
  async def process_input(text: str):
51
  global isBusy
 
 
52
  isBusy = True
53
  generator = None
54
  if text and len(text.strip()) > 0:
 
57
  streaming_response = session_assistant.ask(text)
58
  generator = streaming_response.response_gen
59
  else:
60
+ message = "Please provide the PDF document you'd like to add."
61
  generator = re.split(r'(\s)', message)
62
  else:
63
+ message = "Your query is empty. Please provide a query for me to process."
64
  generator = re.split(r'(\s)', message)
 
65
  return StreamingResponse(astreamer(generator), media_type='text/event-stream')
66
 
 
 
 
67
 
68
  @app.post("/upload")
69
+ def upload(files: list[UploadFile]):
70
  global isBusy
 
 
71
  isBusy = True
72
+ try:
73
+ os.makedirs(files_dir)
74
+ for file in files:
75
+ try:
76
+ path = f"{files_dir}/{file.filename}"
77
+ file.file.seek(0)
78
+ with open(path, 'wb') as destination:
79
+ shutil.copyfileobj(file.file, destination)
80
+ finally:
81
+ file.file.close()
82
+ finally:
83
+ session_assistant.ingest(files_dir)
84
+ shutil.rmtree(files_dir)
85
+ message = "All files have been added successfully to your account. Your first query may take a little longer as the system indexes your documents. Please be patient while we process your request."
86
  generator = re.split(r'(\s)', message)
 
87
  return StreamingResponse(astreamer(generator), media_type='text/event-stream')
88
 
89
 
90
  @app.get("/clear")
91
  def clear():
92
  global isBusy
93
+ isBusy = True
94
  session_assistant.clear()
95
+ message = "Your files have been cleared successfully."
96
  generator = re.split(r'(\s)', message)
 
97
  return StreamingResponse(astreamer(generator), media_type='text/event-stream')
98
 
99