Update main.py
Browse files
main.py
CHANGED
@@ -1,213 +1,126 @@
|
|
1 |
-
|
2 |
-
from fastapi
|
3 |
-
from fastapi.middleware.cors import CORSMiddleware
|
4 |
-
from
|
5 |
-
from
|
6 |
-
import
|
7 |
-
import
|
8 |
-
|
9 |
-
import
|
10 |
-
from
|
11 |
-
import
|
12 |
-
from
|
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 |
-
document_text,
|
128 |
-
max_length=150,
|
129 |
-
min_length=30,
|
130 |
-
do_sample=False,
|
131 |
-
truncation=True
|
132 |
-
)
|
133 |
-
|
134 |
-
return JSONResponse(
|
135 |
-
content={"status": "success", "result": summary[0]['summary_text']},
|
136 |
-
status_code=200
|
137 |
-
)
|
138 |
-
except Exception as e:
|
139 |
-
raise HTTPException(
|
140 |
-
status_code=500,
|
141 |
-
detail=f"Error processing document: {str(e)}"
|
142 |
-
)
|
143 |
-
|
144 |
-
@app.post("/api/caption")
|
145 |
-
async def generate_image_caption(file: UploadFile = File(...)):
|
146 |
-
"""Generate caption for an image"""
|
147 |
-
initialize_models()
|
148 |
-
|
149 |
-
try:
|
150 |
-
# Save the uploaded image temporarily
|
151 |
-
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as temp_file:
|
152 |
-
temp_file.write(file.file.read())
|
153 |
-
temp_path = temp_file.name
|
154 |
-
|
155 |
-
# Open the image
|
156 |
-
image = Image.open(temp_path)
|
157 |
-
|
158 |
-
# Generate caption with optimized prompt
|
159 |
-
caption = image_captioner(
|
160 |
-
image,
|
161 |
-
generate_kwargs={
|
162 |
-
"max_length": 50,
|
163 |
-
"num_beams": 4,
|
164 |
-
"early_stopping": True
|
165 |
-
}
|
166 |
-
)
|
167 |
-
|
168 |
-
return JSONResponse(
|
169 |
-
content={"status": "success", "result": caption[0]['generated_text']},
|
170 |
-
status_code=200
|
171 |
-
)
|
172 |
-
except Exception as e:
|
173 |
-
raise HTTPException(
|
174 |
-
status_code=500,
|
175 |
-
detail=f"Error processing image: {str(e)}"
|
176 |
-
)
|
177 |
-
finally:
|
178 |
-
if 'temp_path' in locals() and os.path.exists(temp_path):
|
179 |
-
os.unlink(temp_path)
|
180 |
-
|
181 |
-
@app.post("/api/qa")
|
182 |
-
async def answer_question(
|
183 |
-
file: UploadFile = File(...),
|
184 |
-
question: str = Form(...)
|
185 |
-
):
|
186 |
-
"""Answer questions based on document content"""
|
187 |
-
initialize_models()
|
188 |
-
|
189 |
-
try:
|
190 |
-
# Extract text from the document
|
191 |
-
document_text = extract_text_from_file(file)
|
192 |
-
|
193 |
-
# Get answer using the QA chain
|
194 |
-
answer = qa_chain.run(document=document_text, question=question)
|
195 |
-
|
196 |
-
return JSONResponse(
|
197 |
-
content={"status": "success", "result": answer},
|
198 |
-
status_code=200
|
199 |
-
)
|
200 |
-
except Exception as e:
|
201 |
-
raise HTTPException(
|
202 |
-
status_code=500,
|
203 |
-
detail=f"Error processing question: {str(e)}"
|
204 |
-
)
|
205 |
-
|
206 |
-
@app.get("/")
|
207 |
-
async def health_check():
|
208 |
-
"""Health check endpoint"""
|
209 |
-
return {"status": "healthy", "version": "1.0.0"}
|
210 |
-
|
211 |
-
if __name__ == "__main__":
|
212 |
-
import uvicorn
|
213 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
1 |
+
import os
|
2 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
4 |
+
from fastapi.responses import JSONResponse
|
5 |
+
from pydantic import BaseModel
|
6 |
+
from typing import Optional
|
7 |
+
from PIL import Image
|
8 |
+
import pytesseract
|
9 |
+
from transformers import pipeline
|
10 |
+
from langchain.chains import LLMChain
|
11 |
+
from langchain.prompts import PromptTemplate
|
12 |
+
from langchain_community.llms import HuggingFaceHub
|
13 |
+
|
14 |
+
# Ensure HF cache directory is set before any HF import uses it
|
15 |
+
os.environ.setdefault("HF_HOME", os.getenv("HF_HOME", "/app/cache"))
|
16 |
+
|
17 |
+
# FastAPI application
|
18 |
+
app = FastAPI(
|
19 |
+
title="AI-Powered Web Application API",
|
20 |
+
description="API for document summarization, image captioning, and question answering",
|
21 |
+
version="1.0.0"
|
22 |
+
)
|
23 |
+
|
24 |
+
# CORS middleware
|
25 |
+
app.add_middleware(
|
26 |
+
CORSMiddleware,
|
27 |
+
allow_origins=["*"],
|
28 |
+
allow_credentials=True,
|
29 |
+
allow_methods=["*"],
|
30 |
+
allow_headers=["*"],
|
31 |
+
)
|
32 |
+
|
33 |
+
# ----------------
|
34 |
+
# Schemas
|
35 |
+
# ----------------
|
36 |
+
class SummarizeRequest(BaseModel):
|
37 |
+
text: str
|
38 |
+
max_length: Optional[int] = 150
|
39 |
+
min_length: Optional[int] = 40
|
40 |
+
|
41 |
+
class QARequest(BaseModel):
|
42 |
+
question: str
|
43 |
+
context: Optional[str] = None
|
44 |
+
|
45 |
+
# ----------------
|
46 |
+
# Model loaders (lazy)
|
47 |
+
# ----------------
|
48 |
+
_cache_dir = os.getenv("HF_HOME", "/app/cache")
|
49 |
+
_summarizer = None
|
50 |
+
_captioner = None
|
51 |
+
_qa_chain = None
|
52 |
+
|
53 |
+
|
54 |
+
def get_summarizer():
|
55 |
+
global _summarizer
|
56 |
+
if _summarizer is None:
|
57 |
+
_summarizer = pipeline(
|
58 |
+
"summarization",
|
59 |
+
model="facebook/bart-large-cnn",
|
60 |
+
cache_dir=_cache_dir
|
61 |
+
)
|
62 |
+
return _summarizer
|
63 |
+
|
64 |
+
|
65 |
+
def get_image_captioner():
|
66 |
+
global _captioner
|
67 |
+
if _captioner is None:
|
68 |
+
_captioner = pipeline(
|
69 |
+
"image-to-text",
|
70 |
+
model="nlpconnect/vit-gpt2-image-captioning",
|
71 |
+
cache_dir=_cache_dir
|
72 |
+
)
|
73 |
+
return _captioner
|
74 |
+
|
75 |
+
|
76 |
+
def get_qa_chain():
|
77 |
+
global _qa_chain
|
78 |
+
if _qa_chain is None:
|
79 |
+
llm = HuggingFaceHub(
|
80 |
+
repo_id="google/flan-t5-large",
|
81 |
+
model_kwargs={"cache_dir": _cache_dir},
|
82 |
+
huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN", None)
|
83 |
+
)
|
84 |
+
prompt = PromptTemplate(
|
85 |
+
input_variables=["context", "question"],
|
86 |
+
template="""
|
87 |
+
Use the following context to answer the question:
|
88 |
+
|
89 |
+
{context}
|
90 |
+
|
91 |
+
Question: {question}
|
92 |
+
Answer:"""
|
93 |
+
)
|
94 |
+
_qa_chain = LLMChain(llm=llm, prompt=prompt)
|
95 |
+
return _qa_chain
|
96 |
+
|
97 |
+
# ----------------
|
98 |
+
# Routes
|
99 |
+
# ----------------
|
100 |
+
@app.post("/summarize")
|
101 |
+
def summarize(req: SummarizeRequest):
|
102 |
+
summarizer = get_summarizer()
|
103 |
+
result = summarizer(
|
104 |
+
req.text,
|
105 |
+
max_length=req.max_length,
|
106 |
+
min_length=req.min_length,
|
107 |
+
clean_up_tokenization_spaces=True
|
108 |
+
)
|
109 |
+
return JSONResponse(content={"summary": result[0]["summary_text"]})
|
110 |
+
|
111 |
+
@app.post("/caption")
|
112 |
+
async def caption_image(file: UploadFile = File(...)):
|
113 |
+
try:
|
114 |
+
img = Image.open(file.file).convert("RGB")
|
115 |
+
captioner = get_image_captioner()
|
116 |
+
result = captioner(img)
|
117 |
+
return JSONResponse(content={"caption": result[0]["generated_text"]})
|
118 |
+
except Exception as e:
|
119 |
+
raise HTTPException(status_code=400, detail=str(e))
|
120 |
+
|
121 |
+
@app.post("/qa")
|
122 |
+
def question_answer(req: QARequest):
|
123 |
+
chain = get_qa_chain()
|
124 |
+
context = req.context or ""
|
125 |
+
answer = chain.run({"context": context, "question": req.question})
|
126 |
+
return JSONResponse(content={"answer": answer})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|