Spaces:
Running
Running
File size: 9,409 Bytes
ebf76ba 2852c90 2be14bd 1be9899 65aa3e7 dbe3ba4 28de64c a5ffabc 65aa3e7 0c9548a b1622cb 65aa3e7 3fac00e 2be14bd 65aa3e7 9a2af53 3fac00e 239c804 65aa3e7 8e24199 1be9899 65aa3e7 d2931fe 8e24199 d2931fe 8e24199 1be9899 c724805 d2931fe 2be14bd 1be9899 65aa3e7 8e24199 1be9899 65aa3e7 2852c90 3fac00e d2931fe 8e24199 d2931fe 2be14bd 65aa3e7 8e24199 d2931fe 65aa3e7 3fac00e d2931fe 8e24199 d2931fe 2be14bd 65aa3e7 3fac00e 65aa3e7 8e24199 1be9899 65aa3e7 8e24199 3fac00e d2931fe 8e24199 d2931fe 8e24199 65aa3e7 d2931fe 8e24199 65aa3e7 2be14bd 65aa3e7 2852c90 65aa3e7 2be14bd 65aa3e7 2be14bd d2931fe 2be14bd d2931fe 7e5ddc3 d2931fe 65aa3e7 3fac00e 2852c90 2be14bd 3fac00e 08338e1 65aa3e7 1be9899 ebf76ba 6a716a1 ebf76ba 65aa3e7 |
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 |
"""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 torchvision import transforms
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from PIL import Image
from transformers import pipeline
import gradio as gr
from fastapi.responses import RedirectResponse
import numpy as np
# Initialize FastAPI
print("π FastAPI server is starting...")
app = FastAPI()
# Load AI Model for Question Answering (DeepSeek-V2-Chat)
from transformers import AutoModelForCausalLM, AutoTokenizer
# Preload Hugging Face model
print(f"π Loading models")
qa_pipeline = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=-1)
# Load Pretrained Object Detection Model (Torchvision)
from torchvision.models.detection import FasterRCNN_ResNet50_FPN_Weights
weights = FasterRCNN_ResNet50_FPN_Weights.DEFAULT
model = fasterrcnn_resnet50_fpn(weights=weights)
model.eval()
# Image Transformations
transform = transforms.Compose([
transforms.ToTensor()
])
# Allowed File Extensions
ALLOWED_EXTENSIONS = {"pdf", "docx", "pptx", "xlsx"}
def validate_file_type(file):
ext = file.name.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_file):
try:
print("π Extracting text from PDF...")
doc = fitz.open(pdf_file)
text = "\n".join([page.get_text("text") for page in doc])
print("β
PDF text extraction completed.")
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):
try:
print("π Extracting text with Tika...")
parsed = parser.from_buffer(file)
print("β
Tika text extraction completed.")
return parsed.get("content", "β οΈ No text found.").strip()
except Exception as e:
return f"β Error reading document: {str(e)}"
def extract_text_from_pptx(pptx_file):
try:
print("π Extracting text from PPTX...")
ppt = Presentation(pptx_file)
text = []
for slide in ppt.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text.append(shape.text)
print("β
PPTX text extraction completed.")
return "\n".join(text) if text else "β οΈ No text found."
except Exception as e:
return f"β Error reading PPTX: {str(e)}"
def extract_text_from_excel(excel_file):
try:
print("π Extracting text from Excel...")
wb = openpyxl.load_workbook(excel_file, read_only=True)
text = []
for sheet in wb.worksheets:
for row in sheet.iter_rows(values_only=True):
text.append(" ".join(map(str, row)))
print("β
Excel text extraction completed.")
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, question):
print("π Processing document for QA...")
validation_error = validate_file_type(file)
if validation_error:
return validation_error
file_ext = file.name.split(".")[-1].lower()
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)
print("π€ Generating response...")
response = qa_pipeline(f"Question: {question}\nContext: {truncated_text}")
print("β
AI response generated.")
return response[0]["generated_text"]
print("β
Models loaded successfully.")
doc_interface = gr.Interface(fn=answer_question_from_document, inputs=[gr.File(), gr.Textbox()], outputs="text")
demo = gr.TabbedInterface([doc_interface], ["Document QA"])
app = gr.mount_gradio_app(app, demo, path="/")
@app.get("/")
def home():
return RedirectResponse(url="/")
"""
from fastapi import FastAPI, File, UploadFile
import fitz # PyMuPDF for PDF parsing
import openpyxl
from pptx import Presentation
import torch
from torchvision import transforms
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from PIL import Image
from transformers import pipeline
import gradio as gr
from fastapi.responses import RedirectResponse
import numpy as np
import docx
# Initialize FastAPI
print("π FastAPI server is starting...")
app = FastAPI()
# Load AI Model for Question Answering (DeepSeek-V2-Chat)
from transformers import AutoModelForCausalLM, AutoTokenizer
# Preload Hugging Face model
print(f"π Loading models")
qa_pipeline = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=-1)
# Load Pretrained Object Detection Model (Torchvision)
from torchvision.models.detection import FasterRCNN_ResNet50_FPN_Weights
weights = FasterRCNN_ResNet50_FPN_Weights.DEFAULT
model = fasterrcnn_resnet50_fpn(weights=weights)
model.eval()
# Image Transformations
transform = transforms.Compose([
transforms.ToTensor()
])
# Allowed File Extensions
ALLOWED_EXTENSIONS = {"pdf", "docx", "pptx", "xlsx"}
def validate_file_type(file):
ext = file.name.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_file):
try:
print("π Extracting text from PDF...")
doc = fitz.open(pdf_file)
text = "\n".join([page.get_text("text") for page in doc])
print("β
PDF text extraction completed.")
return text if text else "β οΈ No text found."
except Exception as e:
return f"β Error reading PDF: {str(e)}"
def extract_text_from_docx(docx_file):
try:
print("π Extracting text from DOCX...")
doc = docx.Document(docx_file)
text = "\n".join([para.text for para in doc.paragraphs])
print("β
DOCX text extraction completed.")
return text if text else "β οΈ No text found."
except Exception as e:
return f"β Error reading DOCX: {str(e)}"
def extract_text_from_pptx(pptx_file):
try:
print("π Extracting text from PPTX...")
ppt = Presentation(pptx_file)
text = []
for slide in ppt.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text.append(shape.text)
print("β
PPTX text extraction completed.")
return "\n".join(text) if text else "β οΈ No text found."
except Exception as e:
return f"β Error reading PPTX: {str(e)}"
def extract_text_from_excel(excel_file):
try:
print("π Extracting text from Excel...")
wb = openpyxl.load_workbook(excel_file, read_only=True)
text = []
for sheet in wb.worksheets:
for row in sheet.iter_rows(values_only=True):
text.append(" ".join(map(str, row)))
print("β
Excel text extraction completed.")
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, question):
print("π Processing document for QA...")
validation_error = validate_file_type(file)
if validation_error:
return validation_error
file_ext = file.name.split(".")[-1].lower()
if file_ext == "pdf":
text = extract_text_from_pdf(file)
elif file_ext == "docx":
text = extract_text_from_docx(file)
elif file_ext == "pptx":
text = extract_text_from_pptx(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)
print("π€ Generating response...")
response = qa_pipeline(f"Question: {question}\nContext: {truncated_text}")
print("β
AI response generated.")
return response[0]["generated_text"]
print("β
Models loaded successfully.")
doc_interface = gr.Interface(fn=answer_question_from_document, inputs=[gr.File(), gr.Textbox()], outputs="text")
demo = gr.TabbedInterface([doc_interface], ["Document QA"])
app = gr.mount_gradio_app(app, demo, path="/")
@app.get("/")
def home():
return RedirectResponse(url="/")
|