File size: 14,322 Bytes
e8ef368
71c9483
 
a3cc5d4
71c9483
 
3ce5085
a5109c6
db82fa4
246525b
e8ef368
79ceaaf
0842811
71c9483
 
d490720
 
71c9483
 
 
 
 
 
 
 
e8ef368
 
71c9483
 
 
 
1ed7eae
71c9483
 
 
 
 
 
 
 
e6f1ab4
71c9483
 
0842811
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c4f55
 
112e707
 
 
0842811
 
 
 
 
 
 
b5c4f55
 
 
 
 
 
 
 
 
 
 
112e707
 
60fad09
112e707
60fad09
 
 
 
 
 
 
fddb1a0
60fad09
 
 
 
 
 
 
 
 
 
 
 
 
112e707
b5c4f55
 
 
 
3ce5085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87a5f3d
 
3ce5085
ea19a45
e8ef368
 
 
 
 
e59f632
3ce5085
e59f632
 
 
 
 
 
3ce5085
e59f632
a3cc5d4
e59f632
a3cc5d4
 
 
 
 
 
e8ef368
a3cc5d4
 
 
 
 
 
 
 
 
 
 
 
 
e59f632
 
e8ef368
aa9bf16
 
 
 
 
0842811
aa9bf16
 
 
 
 
 
71c9483
aa9bf16
e815298
233ab66
 
 
 
e815298
b5c4f55
233ab66
db40c74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09fd8b1
 
 
 
 
 
 
 
 
 
 
 
 
 
db40c74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09fd8b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db40c74
09fd8b1
 
db40c74
 
b5c4f55
 
1eb7421
db40c74
e8ef368
 
 
 
 
 
 
 
 
 
 
d228bc3
e8ef368
 
 
d228bc3
 
 
 
 
 
 
 
ea3c5b4
09fd8b1
 
 
 
 
24cc195
 
 
b5c4f55
db40c74
 
2bedcbe
0842811
db40c74
 
3ed8bd4
db40c74
3ed8bd4
db40c74
b5a0cbf
b5c4f55
 
c226cdf
 
e8ef368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# import gradio as gr
import os
import torch
from transformers import AutoProcessor, MllamaForConditionalGeneration, TextIteratorStreamer
from PIL import Image
import spaces
import tempfile
import requests
from PyPDF2 import PdfReader
from threading import Thread
from flask import Flask, request, jsonify
import io
import fitz

# Check if we're running in a Hugging Face Space and if SPACES_ZERO_GPU is enabled
# IS_SPACES_ZERO = os.environ.get("SPACES_ZERO_GPU", "0") == "1"
# IS_SPACE = os.environ.get("SPACE_ID", None) is not None

# Determine the device (GPU if available, else CPU)
device = "cuda" if torch.cuda.is_available() else "cpu"
LOW_MEMORY = os.getenv("LOW_MEMORY", "0") == "1"

print(f"Using device: {device}")
print(f"Low memory mode: {LOW_MEMORY}")

app = Flask(__name__)

# Get Hugging Face token from environment variables
HF_TOKEN = os.environ.get('HF_TOKEN')

# Load the model and processor
model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct"
model = MllamaForConditionalGeneration.from_pretrained(
    model_name,
    use_auth_token=HF_TOKEN,
    torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32,
    device_map="auto" if device == "cuda" else None,  # Use device mapping if CUDA is available
)

# Move the model to the appropriate device (GPU if available)
# model.to(device)
processor = AutoProcessor.from_pretrained(model_name, use_auth_token=HF_TOKEN)

def extract_image_from_pdf(pdf_url, dpi=75):
    """
    Extract first page of PDF as image in memory
    
    Args:
        pdf_url (str): URL of PDF
        dpi (int): Image resolution
    
    Returns:
        PIL.Image: First page as image or None
    """
    try:
        # Download PDF
        response = requests.get(pdf_url, timeout=30)
        response.raise_for_status()
        
        # Open PDF from bytes
        pdf_document = fitz.open(stream=response.content, filetype="pdf")
        
        # Get first page
        first_page = pdf_document[0]
        
        # Render page to pixmap
        pix = first_page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
        
        # Convert to PIL Image
        img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
        
        pdf_document.close()
        return img
    
    except Exception as e:
        print(f"Error extracting first page: {e}")
        return None



def predict_image(image_url, text, file_pref):
    try:
        # Download the image from the URL
        # response = requests.get(image_url)
        # response.raise_for_status()  # Raise an error for invalid responses
        # image = Image.open(io.BytesIO(response.content)).convert("RGB")
        if file_pref == 'img':
            response = requests.get(image_url)
            response.raise_for_status()  # Raise an error for invalid responses
            image = Image.open(io.BytesIO(response.content)).convert("RGB")
        else: 
            image = extract_image_from_pdf(image_url)
            
        messages = [
            {"role": "user", "content": [
                {"type": "image"},  # Specify that an image is provided
                {"type": "text", "text": text}  # Add the user-provided text input
            ]}
        ]
        
        # Create the input text using the processor's chat template
        input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
        
        # Process the inputs and move to the appropriate device
        inputs = processor(image, input_text, return_tensors="pt").to(device)

        # outputs = model.generate(**inputs, max_new_tokens=100)
    
        # # Decode the output to return the final response
        # response = processor.decode(outputs[0], skip_special_tokens=True)
               
        # return response

        streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)

        generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=4096)
        generated_text = ""
        
        thread = Thread(target=model.generate, kwargs=generation_kwargs)
        thread.start()
        buffer = ""
        
        for new_text in streamer:
            buffer += new_text
            # generated_text_without_prompt = buffer
            # # time.sleep(0.01)
            # yield buffer
        
        return buffer
        
    except Exception as e:
        raise ValueError(f"Error during prediction: {str(e)}")


def extract_text_from_pdf(pdf_url):
    try:
        response = requests.get(pdf_url)
        response.raise_for_status()
        with tempfile.NamedTemporaryFile(delete=False) as temp_pdf:
            temp_pdf.write(response.content)
            temp_pdf_path = temp_pdf.name
        
        reader = PdfReader(temp_pdf_path)
        text = ""
        for page in reader.pages:
            text += page.extract_text()
        
        os.remove(temp_pdf_path)
        return text
    except Exception as e:
        raise ValueError(f"Error extracting text from PDF: {str(e)}")
# raise HTTPException(status_code=400, detail=f"Error extracting text from PDF: {str(e)}")

@spaces.GPU
def predict_text(text):
    # pdf_text = extract_text_from_pdf('https://arinsight.co/2024_FA_AEC_1200_GR1_GR2.pdf')
    
    text_combined = text # + "\n\nExtracted Text from PDF:\n" + pdf_text
    
    # Prepare the input messages
    messages = [{"role": "user", "content": [{"type": "text", "text": text_combined}]}]
    
    # Create the input text using the processor's chat template
    input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
    
    # Process the inputs and move to the appropriate device
    # inputs = processor(image, input_text, return_tensors="pt").to(device)
    inputs = processor(text=input_text, return_tensors="pt").to("cuda")
    # Generate a response from the model
    # outputs = model.generate(**inputs, max_new_tokens=1024)
    
    # # Decode the output to return the final response
    # response = processor.decode(outputs[0], skip_special_tokens=True, skip_prompt=True)


    streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)

    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048)
    generated_text = ""
    
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()
    buffer = ""
    
    for new_text in streamer:
        buffer += new_text
        # generated_text_without_prompt = buffer
        # # time.sleep(0.01)
        # yield buffer
    
    return buffer


PROMPT = (
    "Extract the following information as per this format:\n"
    "'Course Code:'\n"
    "'Course Name:'\n"
    "'Course Description:'\n"
    "'Course Credits:'\n"
    "'Course Learning Outcomes:'\n"
    "'Delivery Method:'\n"
    "'Prerequisite(s):'\n"
    "'Co-requisite(s):'\n"
    "'Materials:'\n"
    "'Topical Outline:'\n"
    "Do not add anything else except the required information from this text."
)

PROMPT_SKILLS = (
    "Provide skills based on the Lightcast Open Skills Taxonomy in categories as:\n"
    "'Primary Skills' (the degree program or certification),\n"
    "'Secondary Skills', and\n"
    "'Tertiary Skills'."
)


# PROMPT_IMAGE = (
#     "You are a highly intelligent assistant designed to analyze images and extract structured information from them. "
#     "Your task is to analyze the given image of a student's academic record and generate a response in the exact JSON format provided below. "
#     "If any specific information is missing or unavailable in the image, replace the corresponding field with null. "
#     "Ensure the format is consistent, strictly adhering to the structure shown below.\n\n"
#     "Required JSON Format:\n\n"
#     "{\n"
#     '  "student": {\n'
#     '    "name": "string",\n'
#     '    "id": "string",\n'
#     '    "dob": "string",\n'
#     '    "original_start_date": "string",\n'
#     '    "cumulative_gpa": "string",\n'
#     '    "program": "string",\n'
#     '    "status": "string"\n'
#     '  },\n'
#     '  "courses": [\n'
#     '    {\n'
#     '      "transfer_institution": "string",\n'
#     '      "course_code": "string",\n'
#     '      "course_name": "string",\n'
#     '      "credits_attempted": number,\n'
#     '      "credits_earned": number,\n'
#     '      "grade": "string",\n'
#     '      "quality_points": number,\n'
#     '      "semester_code": "string",\n'
#     '      "semester_dates": "string"\n'
#     '    }\n'
#     "    // Additional courses can be added here\n"
#     "  ]\n"
#     "}\n\n"
#     "Instructions:\n\n"
#     "1. Extract the student information and course details as displayed in the image.\n"
#     "2. Use null for any missing or unavailable information.\n"
#     "3. Format the extracted data exactly as shown above. Do not deviate from this structure.\n"
#     "4. Use accurate field names and ensure proper nesting of data (e.g., 'student' and 'courses' sections).\n"
#     "5. The values for numeric fields like credits_attempted, credits_earned, and quality_points should be numbers (not strings).\n"
# )


PROMPT_IMAGE_STUDENT = (
    "You are a highly intelligent assistant designed to analyze images and extract structured information from them. "
    "Your task is to analyze the given image of a student's academic record and generate a response in the exact JSON format provided below. "
    "If any specific information is missing or unavailable in the image, replace the corresponding field with null. "
    "Ensure the format is consistent, strictly adhering to the structure shown below.\n\n"
    "Required JSON Format:\n\n"
    "{\n"
    '  "student": {\n'
    '    "name": "string",\n'
    '    "id": "string",\n'
    '    "dob": "string",\n'
    '    "original_start_date": "string",\n'
    '    "cumulative_gpa": "string",\n'
    '    "program": "string",\n'
    '    "status": "string"\n'
    '  }\n'
    "}\n\n"
    "Instructions:\n\n"
    "1. Extract the student's general information as displayed in the image.\n"
    "2. Use null for any missing or unavailable information.\n"
    "3. Format the extracted data exactly as shown above. Do not deviate from this structure.\n"
    "4. Ensure accurate field names and proper nesting.\n"
    "5. Return only the 'student' section as JSON.\n"
)

PROMPT_IMAGE_COURSES = (
    "You are a highly intelligent assistant designed to analyze images and extract structured information from them. "
    "Your task is to analyze the given image of a student's academic record and generate a response in the exact JSON format provided below. "
    "If any specific information is missing or unavailable in the image, replace the corresponding field with null. "
    "Ensure the format is consistent, strictly adhering to the structure shown below.\n\n"
    "Required JSON Format:\n\n"
    "{\n"
    '  "courses": [\n'
    '    {\n'
    '      "transfer_institution": "string",\n'
    '      "course_code": "string",\n'
    '      "course_name": "string",\n'
    '      "credits_attempted": number,\n'
    '      "credits_earned": number,\n'
    '      "grade": "string",\n'
    '      "quality_points": number,\n'
    '      "semester_code": "string",\n'
    '      "semester_dates": "string"\n'
    '    }\n'
    "    // Additional courses can be added here\n"
    "  ]\n"
    "}\n\n"
    "Instructions:\n\n"
    "1. Extract the course details as displayed in the image.\n"
    "2. Use null for any missing or unavailable information.\n"
    "3. Format the extracted data exactly as shown above. Do not deviate from this structure.\n"
    "4. Ensure accurate field names and proper nesting.\n"
    "5. Return only the 'courses' section as JSON.\n"
)



@app.route("/", methods=["GET"])
def home():
    return jsonify({"message": "Welcome to the PDF Extraction API. Use the /extract endpoint to extract information."})

@app.route("/favicon.ico")
def favicon():
    return "", 204

@app.route("/extract", methods=["POST"])
def extract_info():
    data = request.json
    if not data:
        return jsonify({"error": "Please provide a PDF URL in the request body."}), 400
    
    try:
        if data["url"] is not None:
            pdf_url = data["url"]
            pdf_text = extract_text_from_pdf(pdf_url)
            prompt = f"{PROMPT}\n\n{pdf_text}"
            response = predict_text(prompt)
        else:
            response = ''
            
        if data["skills"] == True:
            if response: 
                prompt_skills = f"{PROMPT_SKILLS} using this information only -- {response}"
                response_skills = predict_text(prompt_skills)
            else:
                response_skills = ''
        else:
            response_skills = ''
            
        if data["img_url"] is not None:
            prompt_student = f"{PROMPT_IMAGE_STUDENT}\n"
            prompt_courses = f"{PROMPT_IMAGE_COURSES}\n"
            img_url = data["img_url"]
            file_pref = data["file_pref"]
            response_student = predict_image(img_url, prompt_student, file_pref)
            response_courses = predict_image(img_url, prompt_courses, file_pref)
            response_image = response_student + response_courses 

            # response_image = {"student": response_student.get("student", {}), "courses": response_courses.get("courses", [])}
            
        else:
            response_image = ''
            
        return jsonify({"extracted_info": response + "\n" + response_skills + "\n" + response_image})

    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)


# # Define the Gradio interface
# interface = gr.Interface(
#     fn=predict_text,
#     inputs=[
#         # gr.Image(type="pil", label="Image Input"),  # Image input with label
#         gr.Textbox(label="Text Input")  # Textbox input with label
#     ],
#     outputs=gr.Textbox(label="Generated Response"),  # Output with a more descriptive label
#     title="Llama 3.2 11B Vision Instruct Demo",  # Title of the interface
#     description="This demo uses Meta's Llama 3.2 11B Vision model to generate responses based on an image and text input.",  # Short description
#     theme="compact"  # Using a compact theme for a cleaner look
# )

# # Launch the interface
# interface.launch(debug=True)