-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathapp.py
More file actions
193 lines (183 loc) · 7.66 KB
/
app.py
File metadata and controls
193 lines (183 loc) · 7.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import os
import tempfile
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import StreamingResponse
from dotenv import load_dotenv
from PathRAG import PathRAG, QueryParam
from PathRAG.llm import azure_openai_complete, azure_openai_complete_stream
# Additional libraries for file processing
import PyPDF2
import docx2txt
from pptx import Presentation
import openpyxl
from striprtf.striprtf import rtf_to_text
from odf.opendocument import load as load_odf
from odf import teletype
from ebooklib import epub
from bs4 import BeautifulSoup
# Initialize FastAPI with Swagger UI metadata.
app = FastAPI(
title="PathRAG API",
description="API for uploading files and querying the RAG system (including streaming responses).",
version="1.0"
)
# Load environment variables from .env.
load_dotenv()
# Setup a working directory for PathRAG.
WORKING_DIR = os.path.join(os.getcwd(), 'data')
if not os.path.exists(WORKING_DIR):
os.mkdir(WORKING_DIR)
# Initialize the RAG instance.
rag = PathRAG(
working_dir=WORKING_DIR,
llm_model_func=azure_openai_complete,
)
def extract_text_from_file(file: UploadFile) -> str:
"""
Extract text from an uploaded file.
Supports many file types including:
.txt, .md, .pdf, .docx, .pptx, .xlsx, .rtf, .odt, .tex, .epub,
.html, .htm, .csv, .json, .xml, .yaml, .yml, .log, .conf, .ini,
.properties, .sql, .bat, .sh, .c, .cpp, .py, .java, .js, .ts,
.swift, .go, .rb, .php, .css, .scss, .less.
"""
filename = file.filename
extension = os.path.splitext(filename)[1].lower()
file.file.seek(0)
# Define plain text file extensions.
plain_text_ext = [
".txt", ".md", ".tex", ".csv", ".json", ".xml", ".yaml", ".yml",
".log", ".conf", ".ini", ".properties", ".sql", ".bat", ".sh",
".c", ".cpp", ".py", ".java", ".js", ".ts", ".swift", ".go",
".rb", ".php", ".css", ".scss", ".less"
]
if extension in plain_text_ext:
try:
return file.file.read().decode('utf-8', errors='ignore')
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error reading {extension} file: {str(e)}")
elif extension == ".pdf":
try:
file.file.seek(0)
pdf_reader = PyPDF2.PdfReader(file.file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() or ""
return text
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing PDF file: {str(e)}")
elif extension == ".docx":
try:
file.file.seek(0)
with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp:
tmp.write(file.file.read())
tmp_path = tmp.name
text = docx2txt.process(tmp_path)
os.remove(tmp_path)
return text
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing DOCX file: {str(e)}")
elif extension == ".pptx":
try:
file.file.seek(0)
with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp:
tmp.write(file.file.read())
tmp_path = tmp.name
prs = Presentation(tmp_path)
text = ""
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text += shape.text + "\n"
os.remove(tmp_path)
return text
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing PPTX file: {str(e)}")
elif extension == ".xlsx":
try:
file.file.seek(0)
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp:
tmp.write(file.file.read())
tmp_path = tmp.name
wb = openpyxl.load_workbook(tmp_path, data_only=True)
text = ""
for sheet in wb.worksheets:
for row in sheet.iter_rows(values_only=True):
row_text = " ".join([str(cell) for cell in row if cell is not None])
text += row_text + "\n"
os.remove(tmp_path)
return text
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing XLSX file: {str(e)}")
elif extension == ".rtf":
try:
file.file.seek(0)
content = file.file.read().decode('utf-8', errors='ignore')
return rtf_to_text(content)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing RTF file: {str(e)}")
elif extension == ".odt":
try:
file.file.seek(0)
with tempfile.NamedTemporaryFile(delete=False, suffix=".odt") as tmp:
tmp.write(file.file.read())
tmp_path = tmp.name
doc = load_odf(tmp_path)
text_content = teletype.extractText(doc)
os.remove(tmp_path)
return text_content
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing ODT file: {str(e)}")
elif extension == ".epub":
try:
file.file.seek(0)
with tempfile.NamedTemporaryFile(delete=False, suffix=".epub") as tmp:
tmp.write(file.file.read())
tmp_path = tmp.name
book = epub.read_epub(tmp_path)
text = ""
for item in book.get_items():
if item.get_type() == epub.ITEM_DOCUMENT:
soup = BeautifulSoup(item.get_content(), "html.parser")
text += soup.get_text() + "\n"
os.remove(tmp_path)
return text
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing EPUB file: {str(e)}")
elif extension in [".html", ".htm"]:
try:
file.file.seek(0)
content = file.file.read().decode('utf-8', errors='ignore')
soup = BeautifulSoup(content, "html.parser")
return soup.get_text()
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing HTML file: {str(e)}")
else:
raise HTTPException(status_code=400, detail="Unsupported file type.")
@app.post("/upload", summary="Upload a file", description="Upload a file to insert its content into the RAG system.")
async def upload_file(file: UploadFile = File(...)):
try:
content = extract_text_from_file(file)
await rag.ainsert(content)
return {"message": f"File '{file.filename}' processed and content inserted."}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/query", summary="Query the RAG system", description="Send a query to the RAG system and receive the generated response.")
async def query_rag(query: str):
try:
result = await rag.aquery(query, param=QueryParam(mode="hybrid"))
return {"query": query, "result": result}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/query_stream", summary="Stream Query the RAG system", description="Send a query to the RAG system and stream the generated response.")
async def query_rag_stream(query: str):
async def stream_generator():
async for chunk in azure_openai_complete_stream(
query,
system_prompt=None,
history_messages=[],
keyword_extraction=False,
param=QueryParam(mode="hybrid")
):
yield chunk
return StreamingResponse(stream_generator(), media_type="text/plain")