sas_opposition_exam_data / generation_script.py
RafaelJaime's picture
Update generation_script.py
0172e34 verified
!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)