File size: 10,154 Bytes
79c8ea7
0540355
0c9548a
0540355
 
 
 
 
 
 
 
 
 
 
 
 
b1622cb
d74850e
 
 
0540355
 
 
 
239c804
0540355
8e24199
0540355
1be9899
0540355
 
 
 
 
 
 
 
 
 
4c11732
753db53
0540355
2be14bd
0540355
4c11732
0540355
2be14bd
0540355
 
 
753db53
 
 
0540355
 
753db53
0540355
 
 
 
 
d74850e
0540355
d74850e
0540355
d74850e
 
 
0540355
 
0b363e7
 
 
4c11732
0540355
 
 
 
 
 
0b363e7
4c11732
0b363e7
4c11732
0b363e7
4c11732
2be14bd
d2931fe
0540355
2be14bd
d2931fe
0540355
7e5ddc3
753db53
 
2852c90
2be14bd
0540355
 
 
 
 
 
 
 
 
 
 
 
01cb6f1
0540355
d74850e
 
79c8ea7
 
 
 
 
 
 
669e074
 
79c8ea7
 
5ebce4d
79c8ea7
 
 
5ebce4d
79c8ea7
 
 
 
 
5ebce4d
 
3403b3e
79c8ea7
5ebce4d
 
79c8ea7
 
 
 
 
 
 
5ebce4d
 
 
 
79c8ea7
 
 
 
5ebce4d
79c8ea7
 
 
 
 
 
 
 
 
2553b67
79c8ea7
5ebce4d
 
2553b67
 
79c8ea7
 
2553b67
79c8ea7
2553b67
5ebce4d
2553b67
 
79c8ea7
 
2553b67
79c8ea7
2553b67
79c8ea7
 
 
 
5ebce4d
2553b67
 
79c8ea7
5ebce4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79c8ea7
5ebce4d
 
 
79c8ea7
 
 
2553b67
3403b3e
1f136e0
 
 
 
 
 
 
 
 
 
 
5ebce4d
171f476
3403b3e
 
5ebce4d
 
 
 
 
3403b3e
 
2553b67
5ebce4d
2553b67
3403b3e
1f136e0
 
 
 
 
 
5ebce4d
 
171f476
 
79c8ea7
5ebce4d
1f136e0
79c8ea7
1f136e0
 
79c8ea7
1f136e0
 
 
 
79c8ea7
5ebce4d
79c8ea7
 
 
 
 
 
 
 
 
 
 
 
d74850e
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""import gradio as gr
import uvicorn
import numpy as np
import fitz  # PyMuPDF
import tika
import torch
from fastapi import FastAPI
from transformers import pipeline
from PIL import Image
from io import BytesIO
from starlette.responses import RedirectResponse
from tika import parser
from openpyxl import load_workbook

# Initialize Tika for DOCX & PPTX parsing
tika.initVM()

# Initialize FastAPI
app = FastAPI()

# Load models
device = "cuda" if torch.cuda.is_available() else "cpu"
qa_pipeline = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=device)
image_captioning_pipeline = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")

ALLOWED_EXTENSIONS = {"pdf", "docx", "pptx", "xlsx"}

# βœ… Function to Validate File Type
def validate_file_type(file):
    if isinstance(file, str):  # Text-based input (NamedString)
        return None
    if hasattr(file, "name"):
        ext = file.name.split(".")[-1].lower()
        if ext not in ALLOWED_EXTENSIONS:
            return f"❌ Unsupported file format: {ext}"
        return None
    return "❌ Invalid file format!"

# βœ… Extract Text from PDF
def extract_text_from_pdf(pdf_bytes):
    doc = fitz.open(stream=pdf_bytes, filetype="pdf")
    return "\n".join([page.get_text() for page in doc])

# βœ… Extract Text from DOCX & PPTX using Tika
def extract_text_with_tika(file_bytes):
    return parser.from_buffer(file_bytes)["content"]

# βœ… Extract Text from Excel
def extract_text_from_excel(file_bytes):
    wb = load_workbook(BytesIO(file_bytes), data_only=True)
    text = []
    for sheet in wb.worksheets:
        for row in sheet.iter_rows(values_only=True):
            text.append(" ".join(str(cell) for cell in row if cell))
    return "\n".join(text)

# βœ… Truncate Long Text for Model
def truncate_text(text, max_length=2048):
    return text[:max_length] if len(text) > max_length else text

# βœ… Answer Questions from Image or Document
def answer_question(file, question: str):
    # Image Processing (Gradio sends images as NumPy arrays)
    if isinstance(file, np.ndarray):  
        image = Image.fromarray(file)
        caption = image_captioning_pipeline(image)[0]['generated_text']
        response = qa_pipeline(f"Question: {question}\nContext: {caption}")
        return response[0]["generated_text"]

    # Validate File
    validation_error = validate_file_type(file)
    if validation_error:
        return validation_error

    file_ext = file.name.split(".")[-1].lower() if hasattr(file, "name") else None
    file_bytes = file.read() if hasattr(file, "read") else None
    if not file_bytes:
        return "❌ Could not read file content!"

    # Extract Text from Supported Documents
    if file_ext == "pdf":
        text = extract_text_from_pdf(file_bytes)
    elif file_ext in ["docx", "pptx"]:
        text = extract_text_with_tika(file_bytes)
    elif file_ext == "xlsx":
        text = extract_text_from_excel(file_bytes)
    else:
        return "❌ Unsupported file format!"

    if not text:
        return "⚠️ No text extracted from the document."

    truncated_text = truncate_text(text)
    response = qa_pipeline(f"Question: {question}\nContext: {truncated_text}")

    return response[0]["generated_text"]

# βœ… Gradio Interface (Unified for Images & Documents)
with gr.Blocks() as demo:
    gr.Markdown("## πŸ“„ AI-Powered Document & Image QA")

    with gr.Row():
        file_input = gr.File(label="Upload Document / Image")
        question_input = gr.Textbox(label="Ask a Question", placeholder="What is this document about?")
    
    answer_output = gr.Textbox(label="Answer")
    
    submit_btn = gr.Button("Get Answer")
    submit_btn.click(answer_question, inputs=[file_input, question_input], outputs=answer_output)

# βœ… Mount Gradio with FastAPI
app = gr.mount_gradio_app(app, demo, path="/")

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

# βœ… Run FastAPI + Gradio
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)
""" 
import gradio as gr
import uvicorn
import numpy as np
import pymupdf 
import tika
import torch
from fastapi import FastAPI
from transformers import pipeline, AutoTokenizer
from PIL import Image
from io import BytesIO
from starlette.responses import RedirectResponse
from tika import parser
from openpyxl import load_workbook
from pptx import Presentation
import easyocr
import os

tika.initVM() 

app = FastAPI()

# Load models
device = "cuda" if torch.cuda.is_available() else "cpu"
qa_pipeline = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=device)
image_captioning_pipeline = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")

tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
reader = easyocr.Reader(["en"])  

ALLOWED_EXTENSIONS = {"pdf", "docx", "pptx", "xlsx", "png", "jpg", "jpeg"}

def validate_file_type(file):
    if file is None:
        return "❌ No file uploaded!"
    if isinstance(file, str):  
        return None
    if hasattr(file, "name"):
        ext = file.name.split(".")[-1].lower()
        if ext not in ALLOWED_EXTENSIONS:
            return f"❌ Unsupported file format: {ext}"
        return None
    return "❌ Invalid file format!"

# βœ… Extract Text from PDF
def extract_text_from_pdf(file_bytes):
    try:
        doc = pymupdf.open(stream=file_bytes, filetype="pdf")
        return "\n".join([page.get_text("text") for page in doc])
    except Exception as e:
        return f"❌ PDF Error: {str(e)}"

# βœ… Extract Text from DOCX & PPTX using Tika
def extract_text_with_tika(file_bytes):
    try:
        parsed = parser.from_buffer(file_bytes)
        return parsed.get("content", "⚠️ No text found.").strip()
    except Exception as e:
        return f"❌ Tika Error: {str(e)}"

# βœ… Extract Text from Excel
def extract_text_from_excel(file_bytes):
    try:
        wb = load_workbook(BytesIO(file_bytes), data_only=True)
        text = []
        for sheet in wb.worksheets:
            for row in sheet.iter_rows(values_only=True):
                text.append(" ".join(str(cell) for cell in row if cell))
        return "\n".join(text) if text else "⚠️ No text found."
    except Exception as e:
        return f"❌ Excel Error: {str(e)}"

# βœ… Extract Text from PPTX
def extract_text_from_pptx(file_bytes):
    try:
        ppt = Presentation(BytesIO(file_bytes))
        text = []
        for slide in ppt.slides:
            for shape in slide.shapes:
                if hasattr(shape, "text"):
                    text.append(shape.text)
        return "\n".join(text) if text else "⚠️ No text found."
    except Exception as e:
        return f"❌ PPTX Error: {str(e)}"

# βœ… Extract Text from Image using OCR
def extract_text_from_image(image_file):
    try:
        image = Image.open(image_file).convert("RGB")
        np_image = np.array(image)
        
        if np_image.std() < 10:  # Low contrast check
            return "⚠️ No meaningful content detected in the image."
        
        result = reader.readtext(np_image)
        return " ".join([res[1] for res in result]) if result else "⚠️ No text found."
    except Exception as e:
        return f"❌ Image OCR Error: {str(e)}"

# βœ… Truncate Long Text for Model
def truncate_text(text, max_tokens=450):
    tokens = tokenizer.tokenize(text)
    return tokenizer.convert_tokens_to_string(tokens[:max_tokens])

# βœ… Answer Questions from Image or Document
def answer_question(file, question: str):
    try:
        # βœ… Handle Image Files (Gradio sends images as NumPy arrays)
        if isinstance(file, np.ndarray):  
            image = Image.fromarray(file)
            caption = image_captioning_pipeline(image)[0]['generated_text']
            response = qa_pipeline(f"Question: {question}\nContext: {caption}")
            return response[0]["generated_text"]

        # βœ… Validate File
        validation_error = validate_file_type(file)
        if validation_error:
            return validation_error

        # βœ… Read File Bytes
        file_bytes = None
        file_ext = None

        if isinstance(file, str) and os.path.exists(file):
            file_ext = file.split(".")[-1].lower()
            with open(file, "rb") as f:
                file_bytes = f.read()
        elif hasattr(file, "read"):
            file_ext = file.name.split(".")[-1].lower() if hasattr(file, "name") else None
            file_bytes = file.read()
        else:
            return "❌ Unexpected file type received!"

        # βœ… Extract Text Based on File Type
        if file_ext == "pdf":
            text = extract_text_from_pdf(file_bytes)
        elif file_ext in ["docx", "pptx"]:
            text = extract_text_with_tika(file_bytes)
        elif file_ext == "xlsx":
            text = extract_text_from_excel(file_bytes)
        elif file_ext in ["png", "jpg", "jpeg"]:
            text = extract_text_from_image(BytesIO(file_bytes))
        else:
            return f"❌ Unsupported file format: {file_ext}"

        if not text or "⚠️" in text:
            return f"⚠️ No text extracted. Error: {text}"

        truncated_text = truncate_text(text)
        response = qa_pipeline(f"Question: {question}\nContext: {truncated_text}")

        return response[0]["generated_text"]

    except Exception as e:
        return f"❌ Processing Error: {str(e)}"

# βœ… Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("## πŸ“„ AI-Powered Document & Image QA")
    with gr.Row():
        file_input = gr.File(label="Upload Document / Image")
        question_input = gr.Textbox(label="Ask a Question", placeholder="What is this document about?")
    answer_output = gr.Textbox(label="Answer")
    submit_btn = gr.Button("Get Answer")
    submit_btn.click(answer_question, inputs=[file_input, question_input], outputs=answer_output)

# βœ… Mount Gradio with FastAPI
app = gr.mount_gradio_app(app, demo, path="/")

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

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)