{
"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 Number\n",
"Question Text\n",
"\n",
" A\n",
" B\n",
" C\n",
"\n",
"Correct Answer Index (1, 2, or 3)\n",
"yes/no\n",
"\n",
"IMPORTANT:\n",
"- The 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 empty.\n",
"- If the question has an associated image (diagram, symbol, road sign), respond with `yes`.\n",
"- Otherwise, respond with `no`.\n",
"- If the image contains a reference like 'चित्रात दाखवल्याप्रमाणे' (Marathi for \"as shown in the figure\"), ensure `yes`.\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\"(\\d+)\")\n",
" q_pattern = re.compile(r\"(.*?)\")\n",
" choices_pattern = re.compile(r\"(.*?)\", re.DOTALL)\n",
" answer_pattern = re.compile(r\"(.*?)\")\n",
" image_pattern = re.compile(r\"(.*?)\")\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_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": []
}
]
}