File size: 4,743 Bytes
7e5ddc3
2852c90
 
2be14bd
 
1be9899
dbe3ba4
28de64c
a5ffabc
0c9548a
8e24199
b1622cb
1be9899
2be14bd
 
9a2af53
239c804
1be9899
0878e54
1be9899
28de64c
1be9899
 
8e24199
 
 
 
1be9899
28de64c
d2931fe
8e24199
d2931fe
8e24199
 
1be9899
c724805
 
d2931fe
 
 
2be14bd
1be9899
 
8e24199
1be9899
28de64c
2852c90
d2931fe
8e24199
d2931fe
2be14bd
1be9899
8e24199
d2931fe
1be9899
d2931fe
8e24199
d2931fe
2be14bd
1be9899
8e24199
1be9899
 
8e24199
 
 
 
d2931fe
8e24199
d2931fe
8e24199
28de64c
d2931fe
8e24199
 
 
2be14bd
28de64c
1be9899
 
2be14bd
1be9899
2852c90
1be9899
2be14bd
1be9899
2be14bd
d2931fe
8e24199
2be14bd
d2931fe
7e5ddc3
 
d2931fe
0878e54
7e5ddc3
2852c90
2be14bd
1be9899
6bf4ee9
1be9899
 
 
28de64c
1be9899
6bf4ee9
 
 
 
 
 
 
 
 
1be9899
a5ffabc
 
d2931fe
a5ffabc
d2931fe
a5ffabc
 
7e5ddc3
 
1be9899
7e5ddc3
1be9899
7e5ddc3
 
1be9899
 
 
 
 
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
from fastapi import FastAPI, File, UploadFile
import fitz  # PyMuPDF for PDF parsing
from tika import parser  # Apache Tika for document parsing
import openpyxl
from pptx import Presentation
import torch
from PIL import Image
from transformers import pipeline
import gradio as gr
import numpy as np
import easyocr

# Initialize FastAPI (not needed for HF Spaces, but kept for flexibility)
app = FastAPI()

print(f"πŸ”„ Loading models")

doc_qa_pipeline = pipeline("text2text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=-1)
image_captioning_pipeline = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")
print("βœ… Models loaded")

# Initialize OCR Model (CPU Mode)
reader = easyocr.Reader(["en"], gpu=False)

# Allowed File Extensions
ALLOWED_EXTENSIONS = {"pdf", "docx", "pptx", "xlsx"}

def validate_file_type(file):
    ext = file.filename.split(".")[-1].lower()
    print(f"πŸ” Validating file type: {ext}")
    if ext not in ALLOWED_EXTENSIONS:
        return f"❌ Unsupported file format: {ext}"
    return None

# Function to truncate text to 450 tokens
def truncate_text(text, max_tokens=450):
    words = text.split()
    truncated = " ".join(words[:max_tokens])
    print(f"βœ‚οΈ Truncated text to {max_tokens} tokens.")
    return truncated

# Document Text Extraction Functions
def extract_text_from_pdf(pdf_bytes):
    try:
        print("πŸ“„ Extracting text from PDF...")
        doc = fitz.open(stream=pdf_bytes, filetype="pdf")
        text = "\n".join([page.get_text("text") for page in doc])
        return text if text else "⚠️ No text found."
    except Exception as e:
        return f"❌ Error reading PDF: {str(e)}"

def extract_text_with_tika(file_bytes):
    try:
        print("πŸ“ Extracting text with Tika...")
        parsed = parser.from_buffer(file_bytes)
        return parsed.get("content", "⚠️ No text found.").strip()
    except Exception as e:
        return f"❌ Error reading document: {str(e)}"

def extract_text_from_excel(excel_bytes):
    try:
        print("πŸ“Š Extracting text from Excel...")
        wb = openpyxl.load_workbook(excel_bytes, read_only=True)
        text = []
        for sheet in wb.worksheets:
            for row in sheet.iter_rows(values_only=True):
                text.append(" ".join(map(str, row)))
        return "\n".join(text) if text else "⚠️ No text found."
    except Exception as e:
        return f"❌ Error reading Excel: {str(e)}"

def answer_question_from_document(file: UploadFile, question: str):
    print("πŸ“‚ Processing document for QA...")
    validation_error = validate_file_type(file)
    if validation_error:
        return validation_error
    
    file_ext = file.filename.split(".")[-1].lower()
    file_bytes = file.file.read()

    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)
    print("πŸ€– Generating response...")
    response = doc_qa_pipeline(f"Question: {question}\nContext: {truncated_text}")
    
    return response[0]["generated_text"]

def answer_question_from_image(image, question):
    try:
        print("πŸ–ΌοΈ Processing image for QA...")
        if isinstance(image, np.ndarray):  # If it's a NumPy array from Gradio
            image = Image.fromarray(image)  # Convert to PIL Image
        
        print("πŸ–ΌοΈ Generating caption for image...")
        caption = image_captioning_pipeline(image)[0]['generated_text']

        print("πŸ€– Answering question based on caption...")
        response = doc_qa_pipeline(f"Question: {question}\nContext: {caption}")

        return response[0]["generated_text"]
    except Exception as e:
        return f"❌ Error processing image: {str(e)}"

# Gradio UI for Document & Image QA
doc_interface = gr.Interface(
    fn=answer_question_from_document,
    inputs=[gr.File(label="πŸ“‚ Upload Document"), gr.Textbox(label="πŸ’¬ Ask a Question")],
    outputs="text",
    title="πŸ“„ AI Document Question Answering"
)

img_interface = gr.Interface(
    fn=answer_question_from_image,
    inputs=[gr.Image(label="πŸ–ΌοΈ Upload Image"), gr.Textbox(label="πŸ’¬ Ask a Question")],
    outputs="text",
    title="πŸ–ΌοΈ AI Image Question Answering"
)

# Launch Gradio
app = gr.TabbedInterface([doc_interface, img_interface], ["πŸ“„ Document QA", "πŸ–ΌοΈ Image QA"])

if __name__ == "__main__":
    app.launch(share=True)  # For Hugging Face Spaces