scrape / app.py
Suman2003's picture
Update app.py
1cf62ee verified
Raw History Blame Contribute Delete
4.24 kB
import os
import json
import tempfile
import torch
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pdf2image import convert_from_path
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
print("Loading Qwen2-VL-2B on CPU... This will take a moment.")
# Load the model in standard float32 for CPU compatibility
model = Qwen2VLForConditionalGeneration.from_pretrained(
"Qwen/Qwen2-VL-2B-Instruct",
torch_dtype=torch.float32,
device_map="cpu"
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
print("Model loaded and ready!")
@app.post("/extract-chapters")
async def extract_chapters(file: UploadFile = File(...)):
temp_pdf_path = None
try:
contents = await file.read()
# 1. Save uploaded PDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
temp_file.write(contents)
temp_pdf_path = temp_file.name
print("Converting PDF to images (First 10 pages to save CPU)...")
# 2. Convert only the first 10 pages to images to find the TOC
images = convert_from_path(temp_pdf_path, first_page=1, last_page=10)
if not images:
return {"message": "Could not extract images from PDF", "chapters": []}
# 3. Format the request for Qwen2-VL
# We pass the images and the strict instruction prompt
vision_content = [{"type": "image", "image": img} for img in images]
vision_content.append({
"type": "text",
"text": """
You are a strict data parser. Look at these pages and find the Bengali Table of Contents (সূচিপত্র).
Extract the titles of all the stories (গল্প), poems (কবিতা), and essays.
RULES:
1. Output EXACTLY a JSON array of strings containing ONLY the titles.
2. Do NOT include author names or page numbers.
3. Example: ["ভরদুপুরে", "শংকর সেনাপতি"]
"""
})
messages = [
{"role": "user", "content": vision_content}
]
# 4. Prepare inputs for the CPU
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
print("Running AI inference on CPU... (Please wait 1-3 minutes)")
# 5. Generate Response (Greedy decoding for strict JSON)
generated_ids = model.generate(**inputs, max_new_tokens=512, do_sample=False)
# Trim the input prompt from the output
generated_ids_trimmed = [
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)[0]
# 6. Parse JSON safely
try:
# Strip markdown if Qwen adds it (e.g., ```json ... ```)
clean_text = output_text.strip().strip('```json').strip('```').strip()
chapters = json.loads(clean_text)
return {"message": "Extracted via Local Qwen2-VL (CPU)", "chapters": chapters}
except json.JSONDecodeError:
print("Failed to parse AI output as JSON. Raw:", output_text)
return {"message": "AI found text but failed JSON format.", "raw_output": output_text, "chapters": []}
except Exception as e:
print(f"Extraction Error: {e}")
return {"message": "Failed to parse PDF", "error": str(e)}
finally:
if temp_pdf_path and os.path.exists(temp_pdf_path):
os.remove(temp_pdf_path)