File size: 11,419 Bytes
396b136 9cc94be 0172e34 9cc94be 396b136 9faa201 396b136 9faa201 396b136 |
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 |
!pip install PyPDF2 google google-genai requests python-dotenv datasets huggingface_hub
"""# Libraries"""
import os
import requests
import json
from bs4 import BeautifulSoup
import PyPDF2
from google import genai
from google.genai import types
from dotenv import load_dotenv
import pandas as pd
from datasets import Dataset
from huggingface_hub import login
"""# Configure apikey"""
# TODO: Add your own apikey
load_dotenv()
GEMINI_API_KEY = ""
HF_TOKEN= ""
HF_DATASET_NAME=""
"""# Get files"""
# Main page URL
main_url = 'https://www.sspa.juntadeandalucia.es/servicioandaluzdesalud/profesionales/ofertas-de-empleo/oferta-de-empleo-publico-puestos-base/oep-extraordinaria-decreto-ley-122022-centros-sas/cuadro-de-evolucion-concurso-oposicion-centros-sas'
# Main folder where exams will be saved
exams_folder = "exams"
os.makedirs(exams_folder, exist_ok=True)
# Perform an HTTP GET request to the main page
main_response = requests.get(main_url)
if main_response.status_code == 200:
main_soup = BeautifulSoup(main_response.content, 'html.parser')
# Find all tables on the main page
tables = main_soup.find_all('table')
for table in tables:
links = table.find_all('a', href=True)
for link in links:
secondary_url = link['href']
if secondary_url.startswith('/'):
secondary_url = 'https://www.sspa.juntadeandalucia.es' + secondary_url
folder_name = link.text.strip().replace("/", "-") # Replace invalid characters
folder_path = os.path.join(exams_folder, folder_name)
os.makedirs(folder_path, exist_ok=True)
secondary_response = requests.get(secondary_url)
if secondary_response.status_code == 200:
secondary_soup = BeautifulSoup(secondary_response.content, 'html.parser')
secondary_tables = secondary_soup.find_all('table')
for secondary_table in secondary_tables:
exam_booklet_links = secondary_table.find_all('a', title='Cuadernillo de Examen', href=True)
answer_sheet_links = secondary_table.find_all('a', title='Plantilla de respuestas', href=True)
for exam_booklet_link in exam_booklet_links:
pdf_url = exam_booklet_link['href']
if pdf_url.startswith('/'):
pdf_url = 'https://www.sspa.juntadeandalucia.es' + pdf_url
pdf_response = requests.get(pdf_url)
if pdf_response.status_code == 200:
file_path = os.path.join(folder_path, 'Exam_Booklet.pdf')
with open(file_path, 'wb') as pdf_file:
pdf_file.write(pdf_response.content)
print(f'Exam Booklet saved at: {file_path}')
for answer_sheet_link in answer_sheet_links:
pdf_url = answer_sheet_link['href']
if pdf_url.startswith('/'):
pdf_url = 'https://www.sspa.juntadeandalucia.es' + pdf_url
pdf_response = requests.get(pdf_url)
if pdf_response.status_code == 200:
file_path = os.path.join(folder_path, 'Answer_Sheet.pdf')
with open(file_path, 'wb') as pdf_file:
pdf_file.write(pdf_response.content)
print(f'Answer Sheet saved at: {file_path}')
else:
print(f'Error accessing the main page: {main_response.status_code}')
"""# PDF processing
## Extract text
"""
def extract_text_from_pdf(pdf_path: str) -> str:
with open(pdf_path, "rb") as file:
reader = PyPDF2.PdfReader(file)
text = ""
for page in reader.pages:
text += page.extract_text()
return text
"""## Number of questions"""
import base64
import os
from google import genai
from google.genai import types
def generate_number_questions(text):
client = genai.Client(
api_key=GEMINI_API_KEY,
)
model = "gemini-2.0-flash"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text=f"""tell me how many questions you have in format {{"number": "numberofquestionsinteger"}} in the following text: {text}"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
temperature=1,
top_p=0.95,
top_k=40,
max_output_tokens=8192,
response_mime_type="application/json",
)
response = client.models.generate_content(
model=model,
contents=contents,
config=generate_content_config,
)
return response.candidates[0].content.parts[0].text
"""## Process with llm"""
import json
import os
from google import genai
from google.genai import types
def process_with_gemini(text: str, start: int, end: int):
client = genai.Client(
api_key=GEMINI_API_KEY
)
model = "gemini-2.0-flash"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text=f"""
Given the following text of an exam with questions and answers, extract each question and its possible answers.
Format the output as a list of JSON with the following format, I want you to extract questions from {start} to {end}:
{{{{"question number in integer format": {{"statement": "question text", "answers": ["option A", "option B", ...]}}}}}}
Exam text:
{text}
"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
temperature=1,
top_p=0.95,
top_k=40,
max_output_tokens=32768,
response_mime_type="application/json",
)
# Use generate_content() instead of streaming
response = client.models.generate_content(
model=model,
contents=contents,
config=generate_content_config,
)
return response.text # Return the response instead of printing it
"""# Collect the questions"""
import json
import os
from google import genai
from google.genai import types
def process_answers_with_gemini(text: str):
client = genai.Client(
api_key=GEMINI_API_KEY
)
model = "gemini-2.0-flash"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text=f"""
Please return the question number and the correct answers in format ['question number': 'answer letter','question number': 'answer letter'] from the following text
{text}
"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
temperature=1,
top_p=0.95,
top_k=40,
max_output_tokens=32768,
response_mime_type="application/json",
)
# Use generate_content() instead of streaming
response = client.models.generate_content(
model=model,
contents=contents,
config=generate_content_config,
)
return response.text # Return the response instead of printing it
def process_pdf_file(pdf_path: str, answers_pdf_path: str, theme: str) -> pd.DataFrame:
pdf_text = extract_text_from_pdf(pdf_path)
result = generate_number_questions(pdf_text)
question_text = extract_text_from_pdf(answers_pdf_path)
# Process number of questions
try:
result_dict = json.loads(result)
except json.JSONDecodeError:
print("Error: The question count response is not valid JSON.")
return pd.DataFrame()
question_count = result_dict.get("number", "unknown")
print(f"The exam {pdf_path} contains {question_count} questions.")
try:
question_count = int(result_dict.get("number", 0))
except ValueError:
print(f"Error: Could not convert question count '{question_count}' to integer.")
return pd.DataFrame()
# Process questions in batches
questions = []
batch_size = 50
for start in range(1, question_count + 1, batch_size):
end = min(start + batch_size - 1, question_count)
print(f"Processing questions from {pdf_path} {start}-{end}...")
questions_subset = process_with_gemini(pdf_text, start, end)
questions.append(questions_subset)
# Combine all processed question batches
all_questions = []
for question_set in questions:
try:
question_list = json.loads(question_set)
all_questions.extend(question_list)
except json.JSONDecodeError:
print(f"Error: A question batch response is not valid JSON.")
continue
# If no valid questions were processed, return empty DataFrame
if not all_questions:
print("Error: No valid questions were processed.")
return pd.DataFrame()
# Process questions answers
questions_answer = process_answers_with_gemini(question_text)
try:
json_questions_answers = json.loads(questions_answer)
except json.JSONDecodeError:
print("Error: The response is not a valid JSON.")
# Format the data for the DataFrame
processed_data = []
for item in all_questions:
for key, value in item.items():
try:
correct_answer = json_questions_answers[0].get(str(key), "Not available")
processed_data.append({
'id': key,
'statement': value['statement'],
'answers': value['answers'],
'correct_answer': correct_answer,
'theme': theme
})
except KeyError as e:
print(f"Error: Missing key in question data: {e}")
# Skip this question but continue with others
continue
# Create DataFrame from dictionary list
df = pd.DataFrame(processed_data)
if not df.empty:
df.set_index('id', inplace=True)
return df
all_df_array = []
# Verify that the folder exists
if os.path.exists(exams_folder):
for folder_name in os.listdir(exams_folder):
folder_path = os.path.join(exams_folder, folder_name)
# Verify that it's a folder
if os.path.isdir(folder_path):
print(f"Processing: {folder_name}")
files = os.listdir(folder_path)
# Initialize question and answer paths
questions_path = None
answers_path = None
# Look for files that start with the desired prefixes
for file in files:
if file.startswith('Exam_Booklet') and not questions_path:
questions_path = os.path.join(folder_path, file)
elif file.startswith('Answer_Sheet') and not answers_path:
answers_path = os.path.join(folder_path, file)
exam_df = process_pdf_file(questions_path, answers_path, folder_name)
if not exam_df.empty:
all_df_array.append(exam_df)
if all_df_array:
df = pd.concat(all_df_array, ignore_index=True) # `ignore_index=True` to avoid duplicates in the index
print(f"Final DataFrame with all questions and answers:\n{df}")
else:
print("No valid DataFrames were generated.")
"""# Upload to huggingface"""
login(HF_TOKEN)
Dataset.from_pandas(df).push_to_hub(HF_DATASET_NAME) |