Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,89 +1,118 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 3 |
-
from
|
| 4 |
-
import
|
| 5 |
-
from
|
| 6 |
-
import
|
| 7 |
-
from
|
| 8 |
-
import
|
| 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 |
-
logger.info(f"Received
|
| 50 |
-
try:
|
| 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 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
from fastapi.responses import RedirectResponse
|
| 5 |
+
from transformers import pipeline
|
| 6 |
+
import logging
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import io
|
| 9 |
+
from docx import Document
|
| 10 |
+
import fitz # PyMuPDF
|
| 11 |
+
|
| 12 |
+
# Configure logging
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
app = FastAPI()
|
| 17 |
+
|
| 18 |
+
# Serve static files (HTML, CSS, JS)
|
| 19 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 20 |
+
|
| 21 |
+
# Load a multimodal model for image captioning and visual question answering
|
| 22 |
+
multimodal_pipeline = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
|
| 23 |
+
|
| 24 |
+
# Load a text-based model for summarization and text question answering
|
| 25 |
+
text_pipeline = pipeline("text2text-generation", model="t5-small")
|
| 26 |
+
|
| 27 |
+
@app.get("/")
|
| 28 |
+
def read_root():
|
| 29 |
+
# Redirect to the static HTML file
|
| 30 |
+
return RedirectResponse(url="/static/index.html")
|
| 31 |
+
|
| 32 |
+
@app.post("/summarize")
|
| 33 |
+
async def summarize_text(file: UploadFile = File(...)):
|
| 34 |
+
logger.info(f"Received document for summarization: {file.filename}")
|
| 35 |
+
try:
|
| 36 |
+
# Extract text from the document
|
| 37 |
+
text = await extract_text_from_file(file)
|
| 38 |
+
|
| 39 |
+
# Use the text pipeline to summarize the text
|
| 40 |
+
summary = text_pipeline(f"summarize: {text}", max_length=100)
|
| 41 |
+
logger.info(f"Generated summary: {summary[0]['generated_text']}")
|
| 42 |
+
return {"summary": summary[0]['generated_text']}
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.error(f"Error during summarization: {e}")
|
| 45 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 46 |
+
|
| 47 |
+
@app.post("/caption")
|
| 48 |
+
async def caption_image(file: UploadFile = File(...)):
|
| 49 |
+
logger.info(f"Received image for captioning: {file.filename}")
|
| 50 |
+
try:
|
| 51 |
+
# Read the image file
|
| 52 |
+
image_data = await file.read()
|
| 53 |
+
image = Image.open(io.BytesIO(image_data))
|
| 54 |
+
|
| 55 |
+
# Use the multimodal pipeline to generate a caption for the image
|
| 56 |
+
caption = multimodal_pipeline(image)
|
| 57 |
+
logger.info(f"Generated caption: {caption[0]['generated_text']}")
|
| 58 |
+
return {"caption": caption[0]['generated_text']}
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.error(f"Error during image captioning: {e}")
|
| 61 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 62 |
+
|
| 63 |
+
@app.post("/answer")
|
| 64 |
+
async def answer_question(file: UploadFile = File(...), question: str = ""):
|
| 65 |
+
logger.info(f"Received document for question answering: {file.filename}")
|
| 66 |
+
logger.info(f"Received question: {question}")
|
| 67 |
+
try:
|
| 68 |
+
# Extract text from the document
|
| 69 |
+
text = await extract_text_from_file(file)
|
| 70 |
+
|
| 71 |
+
# Use the text pipeline to answer the question
|
| 72 |
+
answer = text_pipeline(f"question: {question} context: {text}")
|
| 73 |
+
logger.info(f"Generated answer: {answer[0]['generated_text']}")
|
| 74 |
+
return {"answer": answer[0]['generated_text']}
|
| 75 |
+
except Exception as e:
|
| 76 |
+
logger.error(f"Error during question answering: {e}")
|
| 77 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 78 |
+
|
| 79 |
+
@app.post("/vqa")
|
| 80 |
+
async def visual_question_answering(file: UploadFile = File(...), question: str = ""):
|
| 81 |
+
logger.info(f"Received image for visual question answering: {file.filename}")
|
| 82 |
+
logger.info(f"Received question: {question}")
|
| 83 |
+
try:
|
| 84 |
+
# Read the image file
|
| 85 |
+
image_data = await file.read()
|
| 86 |
+
image = Image.open(io.BytesIO(image_data))
|
| 87 |
+
|
| 88 |
+
# Use the multimodal pipeline to answer the question about the image
|
| 89 |
+
answer = multimodal_pipeline(image, question=question)
|
| 90 |
+
logger.info(f"Generated answer: {answer[0]['generated_text']}")
|
| 91 |
+
return {"answer": answer[0]['generated_text']}
|
| 92 |
+
except Exception as e:
|
| 93 |
+
logger.error(f"Error during visual question answering: {e}")
|
| 94 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 95 |
+
|
| 96 |
+
# Helper function to extract text from files
|
| 97 |
+
async def extract_text_from_file(file: UploadFile):
|
| 98 |
+
try:
|
| 99 |
+
if file.filename.endswith(".pdf"):
|
| 100 |
+
doc = fitz.open(stream=await file.read(), filetype="pdf")
|
| 101 |
+
text = ""
|
| 102 |
+
for page in doc:
|
| 103 |
+
text += page.get_text()
|
| 104 |
+
return text
|
| 105 |
+
elif file.filename.endswith(".docx"):
|
| 106 |
+
doc = Document(io.BytesIO(await file.read()))
|
| 107 |
+
text = "\n".join([para.text for para in doc.paragraphs])
|
| 108 |
+
return text
|
| 109 |
+
else:
|
| 110 |
+
raise ValueError("Unsupported file format. Please upload a PDF or DOCX file.")
|
| 111 |
+
except Exception as e:
|
| 112 |
+
logger.error(f"Error extracting text from file: {e}")
|
| 113 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 114 |
+
|
| 115 |
+
# Hugging Face Spaces expects the app to be served on port 7860
|
| 116 |
+
if __name__ == "__main__":
|
| 117 |
+
import uvicorn
|
| 118 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|