File size: 24,400 Bytes
7d7af4b |
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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"source": [
"!pip install openai==0.28"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ROE6pVjqkT-L",
"outputId": "01c9f4da-81a9-43ed-c3ac-572e96880a2b"
},
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Collecting openai==0.28\n",
" Downloading openai-0.28.0-py3-none-any.whl.metadata (13 kB)\n",
"Requirement already satisfied: requests>=2.20 in /usr/local/lib/python3.11/dist-packages (from openai==0.28) (2.32.3)\n",
"Requirement already satisfied: tqdm in /usr/local/lib/python3.11/dist-packages (from openai==0.28) (4.67.1)\n",
"Requirement already satisfied: aiohttp in /usr/local/lib/python3.11/dist-packages (from openai==0.28) (3.11.11)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests>=2.20->openai==0.28) (3.4.1)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests>=2.20->openai==0.28) (3.10)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests>=2.20->openai==0.28) (2.3.0)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests>=2.20->openai==0.28) (2024.12.14)\n",
"Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (2.4.4)\n",
"Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (1.3.2)\n",
"Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (25.1.0)\n",
"Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (1.5.0)\n",
"Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (6.1.0)\n",
"Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (0.2.1)\n",
"Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->openai==0.28) (1.18.3)\n",
"Downloading openai-0.28.0-py3-none-any.whl (76 kB)\n",
"\u001b[2K \u001b[90mโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\u001b[0m \u001b[32m76.5/76.5 kB\u001b[0m \u001b[31m3.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hInstalling collected packages: openai\n",
" Attempting uninstall: openai\n",
" Found existing installation: openai 1.59.9\n",
" Uninstalling openai-1.59.9:\n",
" Successfully uninstalled openai-1.59.9\n",
"Successfully installed openai-0.28.0\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!pip install pdf2image\n",
"!sudo apt-get install poppler-utils\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "-QwkjUM-lCOS",
"outputId": "02d87d12-9026-4601-a3ad-f92ea74c3a6c"
},
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Collecting pdf2image\n",
" Downloading pdf2image-1.17.0-py3-none-any.whl.metadata (6.2 kB)\n",
"Requirement already satisfied: pillow in /usr/local/lib/python3.11/dist-packages (from pdf2image) (11.1.0)\n",
"Downloading pdf2image-1.17.0-py3-none-any.whl (11 kB)\n",
"Installing collected packages: pdf2image\n",
"Successfully installed pdf2image-1.17.0\n",
"Reading package lists... Done\n",
"Building dependency tree... Done\n",
"Reading state information... Done\n",
"The following NEW packages will be installed:\n",
" poppler-utils\n",
"0 upgraded, 1 newly installed, 0 to remove and 18 not upgraded.\n",
"Need to get 186 kB of archives.\n",
"After this operation, 696 kB of additional disk space will be used.\n",
"Get:1 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 poppler-utils amd64 22.02.0-2ubuntu0.6 [186 kB]\n",
"Fetched 186 kB in 1s (260 kB/s)\n",
"debconf: unable to initialize frontend: Dialog\n",
"debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 78, <> line 1.)\n",
"debconf: falling back to frontend: Readline\n",
"debconf: unable to initialize frontend: Readline\n",
"debconf: (This frontend requires a controlling tty.)\n",
"debconf: falling back to frontend: Teletype\n",
"dpkg-preconfigure: unable to re-open stdin: \n",
"Selecting previously unselected package poppler-utils.\n",
"(Reading database ... 124950 files and directories currently installed.)\n",
"Preparing to unpack .../poppler-utils_22.02.0-2ubuntu0.6_amd64.deb ...\n",
"Unpacking poppler-utils (22.02.0-2ubuntu0.6) ...\n",
"Setting up poppler-utils (22.02.0-2ubuntu0.6) ...\n",
"Processing triggers for man-db (2.10.2-1) ...\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import openai\n",
"from pdf2image import convert_from_path\n",
"import json\n",
"import pandas as pd\n",
"import os\n",
"import base64\n",
"import re\n",
"\n",
"# OpenAI API Key\n",
"openai.api_key = \"key\"\n",
"\n",
"# Set Paths\n",
"pdf_path = \"/content/QB-MARATHI.pdf\"\n",
"source = \"https://transport.maharashtra.gov.in/Site/Upload/Pdf/QB-MARATHI.pdf\"\n",
"results_folder = \"/content/results\"\n",
"images_folder = os.path.join(results_folder, \"images\")\n",
"os.makedirs(results_folder, exist_ok=True)\n",
"os.makedirs(images_folder, exist_ok=True)\n",
"\n",
"# GPT Prompt\n",
"pre_prompt = \"\"\"Please extract the multiple-choice questions in the attached image in Marathi.\n",
"There can be one or multiple questions per page.\n",
"\n",
"Format the output as:\n",
"<question_num>Question Number</question_num>\n",
"<question>Question Text</question>\n",
"<choices>\n",
" <choice>A</choice>\n",
" <choice>B</choice>\n",
" <choice>C</choice>\n",
"</choices>\n",
"<answer>Correct Answer Index (1, 2, or 3)</answer>\n",
"<image>yes/no</image>\n",
"\n",
"IMPORTANT:\n",
"- The <answer> tag should contain ONLY a single integer: 1, 2, or 3.\n",
"- Do NOT include the actual answer text, only the index.\n",
"- If no answer is available, leave <answer></answer> empty.\n",
"- If the question has an associated image (diagram, symbol, road sign), respond with `<image>yes</image>`.\n",
"- Otherwise, respond with `<image>no</image>`.\n",
"- If the image contains a reference like 'เคเคฟเคคเฅเคฐเคพเคค เคฆเคพเคเคตเคฒเฅเคฏเคพเคชเฅเคฐเคฎเคพเคฃเฅ' (Marathi for \"as shown in the figure\"), ensure `<image>yes</image>`.\n",
"- Ensure options are unique and contain at least two valid choices.\n",
"\"\"\"\n",
"\n",
"# Convert PDF to Images\n",
"def convert_pdf_to_images(pdf_path):\n",
" print(\"๐ Converting PDF to Images...\")\n",
" images = convert_from_path(pdf_path, dpi=300)\n",
" image_paths = []\n",
"\n",
" for i, image in enumerate(images):\n",
" img_path = os.path.join(images_folder, f\"page_{i+1}.png\")\n",
" image.save(img_path, \"PNG\")\n",
" image_paths.append(img_path)\n",
"\n",
" print(f\"โ
{len(image_paths)} images saved.\")\n",
" return image_paths\n",
"\n",
"# Encode Image in Base64\n",
"def encode_image(image_path):\n",
" with open(image_path, \"rb\") as image_file:\n",
" return base64.b64encode(image_file.read()).decode(\"utf-8\")\n",
"\n",
"# Process Image with GPT-4o\n",
"def gpt4o_process_image(image_path):\n",
" base64_image = encode_image(image_path)\n",
"\n",
" try:\n",
" response = openai.ChatCompletion.create(\n",
" model=\"gpt-4o\",\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": pre_prompt},\n",
" {\"role\": \"user\", \"content\": [\n",
" {\"type\": \"text\", \"text\": \"Extract all questions from this image.\"},\n",
" {\"type\": \"image_url\", \"image_url\": {\"url\": f\"data:image/png;base64,{base64_image}\"}}\n",
" ]}\n",
" ],\n",
" max_tokens=2000\n",
" )\n",
"\n",
" extracted_text = response[\"choices\"][0][\"message\"][\"content\"]\n",
" return extracted_text\n",
"\n",
" except json.JSONDecodeError:\n",
" print(\"โ Error: GPT-4o returned an invalid JSON format.\")\n",
" return None\n",
"\n",
"# Parse GPT Response & Fix Issues\n",
"def parse_gpt_output(response):\n",
" # Regex patterns for structured extraction\n",
" q_num_pattern = re.compile(r\"<question_num>(\\d+)</question_num>\")\n",
" q_pattern = re.compile(r\"<question>(.*?)</question>\")\n",
" choices_pattern = re.compile(r\"<choices>(.*?)</choices>\", re.DOTALL)\n",
" answer_pattern = re.compile(r\"<answer>(.*?)</answer>\")\n",
" image_pattern = re.compile(r\"<image>(.*?)</image>\")\n",
"\n",
" # Extract values\n",
" question_nums = q_num_pattern.findall(response)\n",
" questions = q_pattern.findall(response)\n",
" choices_raw = choices_pattern.findall(response)\n",
" answers_raw = answer_pattern.findall(response)\n",
" images_required = image_pattern.findall(response)\n",
"\n",
" # Extract choices correctly & ensure uniqueness\n",
" choices = []\n",
" for choice_text in choices_raw:\n",
" extracted_choices = list(set(re.findall(r\"<choice>(.*?)</choice>\", choice_text))) # Ensure unique choices\n",
" if len(extracted_choices) < 2: # Validator requires at least two options\n",
" extracted_choices.append(\"Option Placeholder\") # Add dummy placeholder\n",
" choices.append(extracted_choices)\n",
"\n",
" # Convert to integer (1,2,3) and validate range\n",
" valid_answers = []\n",
" for answer in answers_raw:\n",
" try:\n",
" int_answer = int(answer.strip())\n",
" if 1 <= int_answer <= 3: # Ensure valid 1-based index\n",
" valid_answers.append(int_answer)\n",
" else:\n",
" valid_answers.append(None)\n",
" except ValueError:\n",
" valid_answers.append(None)\n",
"\n",
" # Ensure all lists have the same length\n",
" min_length = min(len(question_nums), len(questions), len(choices), len(valid_answers), len(images_required))\n",
" question_nums = question_nums[:min_length]\n",
" questions = questions[:min_length]\n",
" choices = choices[:min_length]\n",
" valid_answers = valid_answers[:min_length]\n",
" images_required = images_required[:min_length]\n",
"\n",
" return question_nums, questions, choices, valid_answers, images_required\n",
"\n",
"# Main Execution\n",
"def main():\n",
" image_paths = convert_pdf_to_images(pdf_path)\n",
" all_questions = []\n",
"\n",
" for img_path in image_paths:\n",
" print(f\"๐ท Processing {img_path}...\")\n",
" response = gpt4o_process_image(img_path)\n",
"\n",
" if response:\n",
" q_nums, q_texts, options, correct_answers, images_required = parse_gpt_output(response)\n",
"\n",
" for i in range(len(q_nums)):\n",
" image_info = None\n",
" image_png = None\n",
" image_type = None\n",
"\n",
" if images_required[i] == \"yes\":\n",
" image_png = f\"driving-license-marathi-{q_nums[i]}.png\"\n",
" image_info = \"essential\"\n",
" image_type = \"diagram\"\n",
"\n",
" question_data = {\n",
" \"language\": \"mr\",\n",
" \"country\": \"India\",\n",
" \"file_name\": \"QB-MARATHI.pdf\",\n",
" \"source\": source,\n",
" \"license\": \"Education and Research\",\n",
" \"level\": \"Driver License\",\n",
" \"category_en\": \"Driving\",\n",
" \"category_original_lang\": \"เคกเฅเคฐเคพเคฏเคตเฅเคนเคฟเคเค\",\n",
" \"original_question_num\": int(q_nums[i]),\n",
" \"question\": q_texts[i],\n",
" \"options\": options[i] if i < len(options) else [],\n",
" \"answer\": correct_answers[i], # โ
Always 1,2,3\n",
" \"image_png\": image_png,\n",
" \"image_information\": image_info,\n",
" \"image_type\": image_type,\n",
" \"parallel_question_id\": None\n",
" }\n",
" all_questions.append(question_data)\n",
"\n",
" # Save as JSON\n",
" json_path = os.path.join(results_folder, \"marathi_driving_license_valid.json\")\n",
" with open(json_path, \"w\", encoding=\"utf-8\") as f:\n",
" json.dump(all_questions, f, indent=4, ensure_ascii=False)\n",
"\n",
" # Convert to CSV\n",
" df = pd.DataFrame(all_questions)\n",
" csv_path = os.path.join(results_folder, \"marathi_driving_license_valid.csv\")\n",
" df.to_csv(csv_path, index=False, encoding=\"utf-8\")\n",
"\n",
" print(f\"โ
JSON Saved: {json_path}\")\n",
" print(f\"โ
CSV Saved: {csv_path}\")\n",
"\n",
"# Run the script\n",
"main()\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OgERpYUuTV8k",
"outputId": "b67d003f-5647-45e5-9632-46ae8b10c510"
},
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"๐ Converting PDF to Images...\n",
"โ
107 images saved.\n",
"๐ท Processing /content/results/images/page_1.png...\n",
"๐ท Processing /content/results/images/page_2.png...\n",
"๐ท Processing /content/results/images/page_3.png...\n",
"๐ท Processing /content/results/images/page_4.png...\n",
"๐ท Processing /content/results/images/page_5.png...\n",
"๐ท Processing /content/results/images/page_6.png...\n",
"๐ท Processing /content/results/images/page_7.png...\n",
"๐ท Processing /content/results/images/page_8.png...\n",
"๐ท Processing /content/results/images/page_9.png...\n",
"๐ท Processing /content/results/images/page_10.png...\n",
"๐ท Processing /content/results/images/page_11.png...\n",
"๐ท Processing /content/results/images/page_12.png...\n",
"๐ท Processing /content/results/images/page_13.png...\n",
"๐ท Processing /content/results/images/page_14.png...\n",
"๐ท Processing /content/results/images/page_15.png...\n",
"๐ท Processing /content/results/images/page_16.png...\n",
"๐ท Processing /content/results/images/page_17.png...\n",
"๐ท Processing /content/results/images/page_18.png...\n",
"๐ท Processing /content/results/images/page_19.png...\n",
"๐ท Processing /content/results/images/page_20.png...\n",
"๐ท Processing /content/results/images/page_21.png...\n",
"๐ท Processing /content/results/images/page_22.png...\n",
"๐ท Processing /content/results/images/page_23.png...\n",
"๐ท Processing /content/results/images/page_24.png...\n",
"๐ท Processing /content/results/images/page_25.png...\n",
"๐ท Processing /content/results/images/page_26.png...\n",
"๐ท Processing /content/results/images/page_27.png...\n",
"๐ท Processing /content/results/images/page_28.png...\n",
"๐ท Processing /content/results/images/page_29.png...\n",
"๐ท Processing /content/results/images/page_30.png...\n",
"๐ท Processing /content/results/images/page_31.png...\n",
"๐ท Processing /content/results/images/page_32.png...\n",
"๐ท Processing /content/results/images/page_33.png...\n",
"๐ท Processing /content/results/images/page_34.png...\n",
"๐ท Processing /content/results/images/page_35.png...\n",
"๐ท Processing /content/results/images/page_36.png...\n",
"๐ท Processing /content/results/images/page_37.png...\n",
"๐ท Processing /content/results/images/page_38.png...\n",
"๐ท Processing /content/results/images/page_39.png...\n",
"๐ท Processing /content/results/images/page_40.png...\n",
"๐ท Processing /content/results/images/page_41.png...\n",
"๐ท Processing /content/results/images/page_42.png...\n",
"๐ท Processing /content/results/images/page_43.png...\n",
"๐ท Processing /content/results/images/page_44.png...\n",
"๐ท Processing /content/results/images/page_45.png...\n",
"๐ท Processing /content/results/images/page_46.png...\n",
"๐ท Processing /content/results/images/page_47.png...\n",
"๐ท Processing /content/results/images/page_48.png...\n",
"๐ท Processing /content/results/images/page_49.png...\n",
"๐ท Processing /content/results/images/page_50.png...\n",
"๐ท Processing /content/results/images/page_51.png...\n",
"๐ท Processing /content/results/images/page_52.png...\n",
"๐ท Processing /content/results/images/page_53.png...\n",
"๐ท Processing /content/results/images/page_54.png...\n",
"๐ท Processing /content/results/images/page_55.png...\n",
"๐ท Processing /content/results/images/page_56.png...\n",
"๐ท Processing /content/results/images/page_57.png...\n",
"๐ท Processing /content/results/images/page_58.png...\n",
"๐ท Processing /content/results/images/page_59.png...\n",
"๐ท Processing /content/results/images/page_60.png...\n",
"๐ท Processing /content/results/images/page_61.png...\n",
"๐ท Processing /content/results/images/page_62.png...\n",
"๐ท Processing /content/results/images/page_63.png...\n",
"๐ท Processing /content/results/images/page_64.png...\n",
"๐ท Processing /content/results/images/page_65.png...\n",
"๐ท Processing /content/results/images/page_66.png...\n",
"๐ท Processing /content/results/images/page_67.png...\n",
"๐ท Processing /content/results/images/page_68.png...\n",
"๐ท Processing /content/results/images/page_69.png...\n",
"๐ท Processing /content/results/images/page_70.png...\n",
"๐ท Processing /content/results/images/page_71.png...\n",
"๐ท Processing /content/results/images/page_72.png...\n",
"๐ท Processing /content/results/images/page_73.png...\n",
"๐ท Processing /content/results/images/page_74.png...\n",
"๐ท Processing /content/results/images/page_75.png...\n",
"๐ท Processing /content/results/images/page_76.png...\n",
"๐ท Processing /content/results/images/page_77.png...\n",
"๐ท Processing /content/results/images/page_78.png...\n",
"๐ท Processing /content/results/images/page_79.png...\n",
"๐ท Processing /content/results/images/page_80.png...\n",
"๐ท Processing /content/results/images/page_81.png...\n",
"๐ท Processing /content/results/images/page_82.png...\n",
"๐ท Processing /content/results/images/page_83.png...\n",
"๐ท Processing /content/results/images/page_84.png...\n",
"๐ท Processing /content/results/images/page_85.png...\n",
"๐ท Processing /content/results/images/page_86.png...\n",
"๐ท Processing /content/results/images/page_87.png...\n",
"๐ท Processing /content/results/images/page_88.png...\n",
"๐ท Processing /content/results/images/page_89.png...\n",
"๐ท Processing /content/results/images/page_90.png...\n",
"๐ท Processing /content/results/images/page_91.png...\n",
"๐ท Processing /content/results/images/page_92.png...\n",
"๐ท Processing /content/results/images/page_93.png...\n",
"๐ท Processing /content/results/images/page_94.png...\n",
"๐ท Processing /content/results/images/page_95.png...\n",
"๐ท Processing /content/results/images/page_96.png...\n",
"๐ท Processing /content/results/images/page_97.png...\n",
"๐ท Processing /content/results/images/page_98.png...\n",
"๐ท Processing /content/results/images/page_99.png...\n",
"๐ท Processing /content/results/images/page_100.png...\n",
"๐ท Processing /content/results/images/page_101.png...\n",
"๐ท Processing /content/results/images/page_102.png...\n",
"๐ท Processing /content/results/images/page_103.png...\n",
"๐ท Processing /content/results/images/page_104.png...\n",
"๐ท Processing /content/results/images/page_105.png...\n",
"๐ท Processing /content/results/images/page_106.png...\n",
"๐ท Processing /content/results/images/page_107.png...\n",
"โ
JSON Saved: /content/results/QB-MARATHI_valid.json\n",
"โ
CSV Saved: /content/results/QB-MARATHI_valid.csv\n"
]
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "tvQrB5J4Ue5Q"
},
"execution_count": null,
"outputs": []
}
]
} |