File size: 3,984 Bytes
95c2451
5b4fc38
3fb07d9
 
40485d4
cf9a79a
3e87c53
3fb07d9
3e87c53
3fb07d9
3e87c53
e5b6ad2
3fb07d9
e5b6ad2
 
 
3fb07d9
1e83db4
a74f8b0
3e87c53
3fb07d9
3e87c53
3fb07d9
 
af32fa4
3fb07d9
 
 
40485d4
af32fa4
 
cf9a79a
3fb07d9
af32fa4
3fb07d9
 
 
af32fa4
 
 
cf9a79a
3fb07d9
af32fa4
3fb07d9
 
 
af32fa4
 
 
 
 
 
 
 
cf9a79a
3fb07d9
af32fa4
3fb07d9
 
 
af32fa4
 
 
 
40485d4
af32fa4
 
 
6dfac5c
af32fa4
3fb07d9
af32fa4
3fb07d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf9a79a
3fb07d9
e5b6ad2
3fb07d9
 
e5b6ad2
3e87c53
95c2451
 
3e87c53
95c2451
e5b6ad2
3e87c53
3fb07d9
 
3e87c53
95c2451
3e87c53
95c2451
3e87c53
 
3fb07d9
3e87c53
3fb07d9
 
5b4fc38
3fb07d9
 
5b4fc38
 
 
3fb07d9
5b4fc38
 
3fb07d9
5b4fc38
 
3e87c53
3fb07d9
5b4fc38
3e87c53
5b4fc38
3fb07d9
5b4fc38
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
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from transformers import pipeline
from PIL import Image
import fitz  # PyMuPDF
import docx
import pptx
import openpyxl
import io

import gradio as gr

# Initialize models
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
image_captioner = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")

# FastAPI app
app = FastAPI()

# -------------------------
# Helper Functions
# -------------------------

def extract_text_from_pdf(upload):
    try:
        file_bytes = upload.read()
        stream = io.BytesIO(file_bytes)
        with fitz.open(stream=stream, filetype="pdf") as doc:
            return "\n".join([page.get_text() for page in doc])
    except Exception as e:
        return f"❌ PDF extraction error: {e}"

def extract_text_from_docx(upload):
    try:
        file_bytes = upload.read()
        stream = io.BytesIO(file_bytes)
        doc = docx.Document(stream)
        return "\n".join(p.text for p in doc.paragraphs if p.text.strip())
    except Exception as e:
        return f"❌ DOCX extraction error: {e}"

def extract_text_from_pptx(upload):
    try:
        file_bytes = upload.read()
        stream = io.BytesIO(file_bytes)
        prs = pptx.Presentation(stream)
        text = []
        for slide in prs.slides:
            for shape in slide.shapes:
                if hasattr(shape, "text"):
                    text.append(shape.text)
        return "\n".join(text)
    except Exception as e:
        return f"❌ PPTX extraction error: {e}"

def extract_text_from_xlsx(upload):
    try:
        file_bytes = upload.read()
        stream = io.BytesIO(file_bytes)
        wb = openpyxl.load_workbook(stream)
        text = []
        for sheet in wb.sheetnames:
            ws = wb[sheet]
            for row in ws.iter_rows(values_only=True):
                text.append(" ".join(str(cell) for cell in row if cell))
        return "\n".join(text)
    except Exception as e:
        return f"❌ XLSX extraction error: {e}"

# -------------------------
# Core Functions
# -------------------------

def summarize_document(upload):
    if not upload:
        return "⚠️ No file uploaded."

    ext = upload.name.lower()
    upload.seek(0)

    if ext.endswith(".pdf"):
        text = extract_text_from_pdf(upload)
    elif ext.endswith(".docx"):
        text = extract_text_from_docx(upload)
    elif ext.endswith(".pptx"):
        text = extract_text_from_pptx(upload)
    elif ext.endswith(".xlsx"):
        text = extract_text_from_xlsx(upload)
    else:
        return "❌ Unsupported file type."

    if not text or not text.strip() or text.startswith("❌"):
        return text if text.startswith("❌") else "❗ No extractable text found."

    try:
        summary = summarizer(text[:3000], max_length=150, min_length=30, do_sample=False)
        return f"πŸ“„ Summary:\n{summary[0]['summary_text']}"
    except Exception as e:
        return f"⚠️ Summarization error: {e}"

def interpret_image(image):
    if not image:
        return "⚠️ No image uploaded."
    try:
        return f"πŸ–ΌοΈ Caption:\n{image_captioner(image)[0]['generated_text']}"
    except Exception as e:
        return f"⚠️ Image captioning error: {e}"

# -------------------------
# Gradio Interface
# -------------------------

doc_ui = gr.Interface(
    fn=summarize_document,
    inputs=gr.File(label="Upload a Document (PDF, DOCX, PPTX, XLSX)"),
    outputs=gr.Textbox(label="Summary"),
    title="πŸ“„ Document Summarizer"
)

img_ui = gr.Interface(
    fn=interpret_image,
    inputs=gr.Image(type="pil", label="Upload an Image"),
    outputs=gr.Textbox(label="Caption"),
    title="πŸ–ΌοΈ Image Interpreter"
)

demo = gr.TabbedInterface([doc_ui, img_ui], ["Document Summarization", "Image Captioning"])
app = gr.mount_gradio_app(app, demo, path="/")

@app.get("/")
def redirect_to_ui():
    return RedirectResponse(url="/")