Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -7,57 +7,56 @@ from openai import OpenAI
|
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
# β
Initialize OpenAI client
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# π Extract text from PDF
|
| 13 |
def extract_pdf_text(file) -> str:
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
text += page_text + "\n"
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@app.post("/Query-pdf")
|
| 23 |
async def query_pdf(query: str = Form(...), pdf: UploadFile = File(...)):
|
| 24 |
try:
|
| 25 |
-
# Extract text from PDF
|
| 26 |
pdf_text = extract_pdf_text(pdf.file)
|
| 27 |
-
|
| 28 |
-
# Restrictive system instruction
|
| 29 |
system_prompt = (
|
| 30 |
"You are a polite and helpful assistant who answers questions strictly using the provided PDF text. "
|
| 31 |
-
"
|
| 32 |
-
"If the requested information cannot be found or confidently inferred from the PDF, "
|
| 33 |
-
"respond kindly and respectfully with: "
|
| 34 |
"'I'm sorry, but the answer is not available in the PDF.'"
|
| 35 |
)
|
| 36 |
|
| 37 |
-
# Call OpenAI GPT model
|
| 38 |
chat_completion = client.chat.completions.create(
|
| 39 |
model="gpt-4o-mini",
|
| 40 |
messages=[
|
| 41 |
{"role": "system", "content": system_prompt},
|
| 42 |
-
{
|
| 43 |
-
"role": "user",
|
| 44 |
-
"content": f"PDF Content:\n{pdf_text[:15000]}\n\nQuery: {query}"
|
| 45 |
-
}
|
| 46 |
],
|
| 47 |
temperature=0.0,
|
| 48 |
max_tokens=1000
|
| 49 |
)
|
| 50 |
|
| 51 |
answer = chat_completion.choices[0].message.content.strip()
|
| 52 |
-
|
| 53 |
-
return JSONResponse({
|
| 54 |
-
"success": True,
|
| 55 |
-
"answer": answer
|
| 56 |
-
})
|
| 57 |
|
| 58 |
except Exception as e:
|
|
|
|
|
|
|
| 59 |
return JSONResponse({"success": False, "error": str(e)})
|
| 60 |
|
| 61 |
@app.get("/")
|
| 62 |
def home():
|
| 63 |
return {"message": "β
Strict PDF Query API is running!"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
# β
Initialize OpenAI client
|
| 10 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
if not api_key:
|
| 12 |
+
raise ValueError("β OPENAI_API_KEY not found. Please add it in Hugging Face Space secrets.")
|
| 13 |
+
client = OpenAI(api_key=api_key)
|
| 14 |
|
| 15 |
# π Extract text from PDF
|
| 16 |
def extract_pdf_text(file) -> str:
|
| 17 |
+
try:
|
| 18 |
+
reader = PyPDF2.PdfReader(file)
|
| 19 |
+
text = ""
|
| 20 |
+
for page in reader.pages:
|
| 21 |
+
page_text = page.extract_text() or ""
|
| 22 |
text += page_text + "\n"
|
| 23 |
+
return text
|
| 24 |
+
except Exception as e:
|
| 25 |
+
raise Exception(f"PDF extraction failed: {e}")
|
| 26 |
|
| 27 |
@app.post("/Query-pdf")
|
| 28 |
async def query_pdf(query: str = Form(...), pdf: UploadFile = File(...)):
|
| 29 |
try:
|
|
|
|
| 30 |
pdf_text = extract_pdf_text(pdf.file)
|
|
|
|
|
|
|
| 31 |
system_prompt = (
|
| 32 |
"You are a polite and helpful assistant who answers questions strictly using the provided PDF text. "
|
| 33 |
+
"If the information is not in the PDF, respond with: "
|
|
|
|
|
|
|
| 34 |
"'I'm sorry, but the answer is not available in the PDF.'"
|
| 35 |
)
|
| 36 |
|
|
|
|
| 37 |
chat_completion = client.chat.completions.create(
|
| 38 |
model="gpt-4o-mini",
|
| 39 |
messages=[
|
| 40 |
{"role": "system", "content": system_prompt},
|
| 41 |
+
{"role": "user", "content": f"PDF Content:\n{pdf_text[:15000]}\n\nQuery: {query}"}
|
|
|
|
|
|
|
|
|
|
| 42 |
],
|
| 43 |
temperature=0.0,
|
| 44 |
max_tokens=1000
|
| 45 |
)
|
| 46 |
|
| 47 |
answer = chat_completion.choices[0].message.content.strip()
|
| 48 |
+
return JSONResponse({"success": True, "answer": answer})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
except Exception as e:
|
| 51 |
+
import traceback
|
| 52 |
+
print("β ERROR:", traceback.format_exc())
|
| 53 |
return JSONResponse({"success": False, "error": str(e)})
|
| 54 |
|
| 55 |
@app.get("/")
|
| 56 |
def home():
|
| 57 |
return {"message": "β
Strict PDF Query API is running!"}
|
| 58 |
+
|
| 59 |
+
# β
Required for Hugging Face Space
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
import uvicorn
|
| 62 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|