File size: 4,239 Bytes
93573a6
 
 
49980fc
93573a6
 
49980fc
 
 
93573a6
 
 
 
 
49980fc
93573a6
 
 
 
 
49980fc
 
 
 
 
 
 
 
 
93573a6
 
 
49980fc
93573a6
 
 
 
49980fc
93573a6
 
49980fc
 
1cf62ee
 
 
49980fc
 
 
 
 
 
 
 
 
 
 
 
93573a6
49980fc
 
 
 
 
 
93573a6
49980fc
 
 
93573a6
49980fc
 
 
93573a6
49980fc
 
 
 
 
 
 
 
 
 
 
93573a6
49980fc
 
 
93573a6
 
49980fc
 
 
93573a6
49980fc
 
 
 
 
 
 
 
 
93573a6
 
49980fc
 
93573a6
 
49980fc
 
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
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)