File size: 3,610 Bytes
1cd6a53
0c9548a
0540355
 
 
 
 
 
 
 
 
 
 
93ae425
0540355
b1622cb
d74850e
 
 
0540355
 
 
93ae425
239c804
0540355
8e24199
0540355
1be9899
0540355
 
 
 
 
 
 
 
93ae425
 
 
2be14bd
0540355
93ae425
 
2be14bd
0540355
93ae425
 
753db53
 
 
0540355
 
753db53
0540355
 
 
 
 
d74850e
93ae425
0540355
d74850e
 
 
0540355
0b363e7
 
 
93ae425
 
0540355
 
0b363e7
93ae425
0b363e7
93ae425
0b363e7
93ae425
2be14bd
d2931fe
0540355
2be14bd
d2931fe
0540355
7e5ddc3
753db53
 
2852c90
2be14bd
93ae425
0540355
 
 
 
93ae425
 
0540355
93ae425
0540355
 
93ae425
0540355
01cb6f1
0540355
f404b85
d74850e
1b0d519
 
f404b85
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
import gradio as gr
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 (Ensure Java is installed)
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="nlpconnect/vit-gpt2-image-captioning")

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

# βœ… Function to Validate File Type
def validate_file_type(file):
    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):
    with fitz.open(file.name) as doc:
        return "\n".join([page.get_text() for page in doc])

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

# βœ… Extract Text from Excel
def extract_text_from_excel(file):
    wb = load_workbook(file.name, 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):
    if isinstance(file, np.ndarray):  # Image Processing
        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"]

    validation_error = validate_file_type(file)
    if validation_error:
        return validation_error
    
    file_ext = file.name.split(".")[-1].lower()

    # Extract Text from Supported Documents
    if file_ext == "pdf":
        text = extract_text_from_pdf(file)
    elif file_ext in ["docx", "pptx"]:
        text = extract_text_with_tika(file)
    elif file_ext == "xlsx":
        text = extract_text_from_excel(file)
    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 (Separate File & Image Inputs)
with gr.Blocks() as demo:
    gr.Markdown("## πŸ“„ AI-Powered Document & Image QA")

    with gr.Row():
        file_input = gr.File(label="Upload Document")
        image_input = gr.Image(label="Upload 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="/")