Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,83 +1,57 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
from PIL import Image
|
4 |
-
import fitz # PyMuPDF for PDF
|
5 |
import docx
|
6 |
-
import pptx
|
7 |
import openpyxl
|
8 |
-
import
|
9 |
-
from
|
10 |
-
|
|
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
|
14 |
image_captioner = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")
|
15 |
-
reader = easyocr.Reader(['en', 'fr'])
|
16 |
|
17 |
-
# FastAPI app
|
18 |
app = FastAPI()
|
19 |
|
20 |
-
#
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
27 |
|
28 |
def extract_text_from_docx(file):
|
29 |
-
|
30 |
-
|
31 |
-
return "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
|
32 |
-
except Exception as e:
|
33 |
-
return f"β Error reading DOCX: {e}"
|
34 |
|
35 |
def extract_text_from_pptx(file):
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
for
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
return "\n".join(text)
|
44 |
-
except Exception as e:
|
45 |
-
return f"β Error reading PPTX: {e}"
|
46 |
|
47 |
def extract_text_from_xlsx(file):
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
image = Image.open(file).convert("RGB")
|
62 |
-
return "\n".join([text[1] for text in reader.readtext(np.array(image))])
|
63 |
-
except Exception as e:
|
64 |
-
return f"β Error reading image with OCR: {e}"
|
65 |
-
|
66 |
-
# Main processing function
|
67 |
-
def analyze_input(file):
|
68 |
-
if file is None:
|
69 |
-
return "Please upload a document or image."
|
70 |
-
|
71 |
-
filename = file.name.lower()
|
72 |
-
ext = filename.split('.')[-1]
|
73 |
-
|
74 |
-
if ext in ["jpg", "jpeg", "png"]:
|
75 |
-
caption = image_captioner(Image.open(file))[0]['generated_text']
|
76 |
-
ocr_text = extract_text_from_image(file)
|
77 |
-
return f"π· Image Caption:\n{caption}\n\nπ OCR Text:\n{ocr_text}"
|
78 |
-
|
79 |
-
elif ext == "pdf":
|
80 |
-
text = extract_text_from_pdf(file.name)
|
81 |
elif ext == "docx":
|
82 |
text = extract_text_from_docx(file)
|
83 |
elif ext == "pptx":
|
@@ -85,28 +59,53 @@ def analyze_input(file):
|
|
85 |
elif ext == "xlsx":
|
86 |
text = extract_text_from_xlsx(file)
|
87 |
else:
|
88 |
-
return "Unsupported file
|
89 |
|
90 |
if not text.strip():
|
91 |
-
return "
|
92 |
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
outputs=gr.Textbox(label="Result", lines=10),
|
101 |
-
title="Document & Image Analysis Web Service",
|
102 |
-
description="Upload a document (PDF, DOCX, PPTX, XLSX) to get a summary or an image to get a caption. OCR and AI-powered."
|
103 |
-
)
|
104 |
-
|
105 |
-
demo = gr.TabbedInterface([iface], ["Docs and Images"])
|
106 |
-
|
107 |
-
# Mount to FastAPI
|
108 |
-
app = gr.mount_gradio_app(app, demo, path="/")
|
109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
@app.get("/")
|
111 |
-
def
|
112 |
-
return
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File
|
2 |
+
import fitz # PyMuPDF
|
|
|
|
|
3 |
import docx
|
|
|
4 |
import openpyxl
|
5 |
+
import pptx
|
6 |
+
from PIL import Image
|
7 |
+
import io
|
8 |
+
|
9 |
+
import gradio as gr
|
10 |
+
from transformers import pipeline
|
11 |
|
12 |
+
# Models
|
13 |
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
|
14 |
image_captioner = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")
|
|
|
15 |
|
|
|
16 |
app = FastAPI()
|
17 |
|
18 |
+
# -------------------------
|
19 |
+
# Document Extraction Utils
|
20 |
+
# -------------------------
|
21 |
+
def extract_text_from_pdf(file):
|
22 |
+
text = ""
|
23 |
+
with fitz.open(stream=file.read(), filetype="pdf") as doc:
|
24 |
+
for page in doc:
|
25 |
+
text += page.get_text()
|
26 |
+
return text
|
27 |
|
28 |
def extract_text_from_docx(file):
|
29 |
+
doc = docx.Document(io.BytesIO(file.read()))
|
30 |
+
return "\n".join([para.text for para in doc.paragraphs if para.text.strip()])
|
|
|
|
|
|
|
31 |
|
32 |
def extract_text_from_pptx(file):
|
33 |
+
text = []
|
34 |
+
prs = pptx.Presentation(io.BytesIO(file.read()))
|
35 |
+
for slide in prs.slides:
|
36 |
+
for shape in slide.shapes:
|
37 |
+
if hasattr(shape, "text"):
|
38 |
+
text.append(shape.text)
|
39 |
+
return "\n".join(text)
|
|
|
|
|
|
|
40 |
|
41 |
def extract_text_from_xlsx(file):
|
42 |
+
wb = openpyxl.load_workbook(io.BytesIO(file.read()))
|
43 |
+
text = []
|
44 |
+
for sheet in wb.sheetnames:
|
45 |
+
ws = wb[sheet]
|
46 |
+
for row in ws.iter_rows(values_only=True):
|
47 |
+
line = " ".join(str(cell) for cell in row if cell)
|
48 |
+
text.append(line)
|
49 |
+
return "\n".join(text)
|
50 |
+
|
51 |
+
def summarize_document(file: UploadFile):
|
52 |
+
ext = file.filename.split(".")[-1].lower()
|
53 |
+
if ext == "pdf":
|
54 |
+
text = extract_text_from_pdf(file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
elif ext == "docx":
|
56 |
text = extract_text_from_docx(file)
|
57 |
elif ext == "pptx":
|
|
|
59 |
elif ext == "xlsx":
|
60 |
text = extract_text_from_xlsx(file)
|
61 |
else:
|
62 |
+
return "Unsupported file format."
|
63 |
|
64 |
if not text.strip():
|
65 |
+
return "No extractable text."
|
66 |
|
67 |
+
# Trim large docs
|
68 |
+
text = text[:3000]
|
69 |
+
try:
|
70 |
+
summary = summarizer(text, max_length=150, min_length=30, do_sample=False)
|
71 |
+
return summary[0]["summary_text"]
|
72 |
+
except Exception as e:
|
73 |
+
return f"Summarization error: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
+
def interpret_image(image):
|
76 |
+
if image is None:
|
77 |
+
return "No image uploaded."
|
78 |
+
try:
|
79 |
+
return image_captioner(image)[0]["generated_text"]
|
80 |
+
except Exception as e:
|
81 |
+
return f"Image captioning error: {e}"
|
82 |
+
|
83 |
+
# -------------------------
|
84 |
+
# Gradio UI
|
85 |
+
# -------------------------
|
86 |
+
def run_interface():
|
87 |
+
doc_summary = gr.Interface(
|
88 |
+
fn=summarize_document,
|
89 |
+
inputs=gr.File(label="Upload a Document"),
|
90 |
+
outputs="text",
|
91 |
+
title="π Document Summarizer"
|
92 |
+
)
|
93 |
+
|
94 |
+
img_caption = gr.Interface(
|
95 |
+
fn=interpret_image,
|
96 |
+
inputs=gr.Image(type="pil", label="Upload an Image"),
|
97 |
+
outputs="text",
|
98 |
+
title="πΌοΈ Image Interpreter"
|
99 |
+
)
|
100 |
+
|
101 |
+
gr.TabbedInterface([doc_summary, img_caption], ["Summarize Document", "Caption Image"]).launch()
|
102 |
+
|
103 |
+
# -------------------------
|
104 |
+
# Run from CLI or FastAPI
|
105 |
+
# -------------------------
|
106 |
@app.get("/")
|
107 |
+
def read_root():
|
108 |
+
return {"message": "Gradio running at /docs or use CLI"}
|
109 |
+
|
110 |
+
if __name__ == "__main__":
|
111 |
+
run_interface()
|