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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
!pip install PyPDF2 google google-genai requests python-dotenv datasets huggingface_hub
|
2 |
+
|
3 |
+
"""# Libraries"""
|
4 |
+
|
5 |
+
import os
|
6 |
+
import requests
|
7 |
+
import json
|
8 |
+
from bs4 import BeautifulSoup
|
9 |
+
import PyPDF2
|
10 |
+
from google import genai
|
11 |
+
from google.genai import types
|
12 |
+
from dotenv import load_dotenv
|
13 |
+
import pandas as pd
|
14 |
+
from datasets import Dataset
|
15 |
+
from huggingface_hub import login
|
16 |
+
|
17 |
+
"""# Get files"""
|
18 |
+
|
19 |
+
# Main page URL
|
20 |
+
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'
|
21 |
+
|
22 |
+
# Main folder where exams will be saved
|
23 |
+
exams_folder = "exams"
|
24 |
+
os.makedirs(exams_folder, exist_ok=True)
|
25 |
+
|
26 |
+
# Perform an HTTP GET request to the main page
|
27 |
+
main_response = requests.get(main_url)
|
28 |
+
|
29 |
+
if main_response.status_code == 200:
|
30 |
+
main_soup = BeautifulSoup(main_response.content, 'html.parser')
|
31 |
+
|
32 |
+
# Find all tables on the main page
|
33 |
+
tables = main_soup.find_all('table')
|
34 |
+
|
35 |
+
for table in tables:
|
36 |
+
links = table.find_all('a', href=True)
|
37 |
+
for link in links:
|
38 |
+
secondary_url = link['href']
|
39 |
+
if secondary_url.startswith('/'):
|
40 |
+
secondary_url = 'https://www.sspa.juntadeandalucia.es' + secondary_url
|
41 |
+
|
42 |
+
folder_name = link.text.strip().replace("/", "-") # Replace invalid characters
|
43 |
+
folder_path = os.path.join(exams_folder, folder_name)
|
44 |
+
os.makedirs(folder_path, exist_ok=True)
|
45 |
+
|
46 |
+
secondary_response = requests.get(secondary_url)
|
47 |
+
if secondary_response.status_code == 200:
|
48 |
+
secondary_soup = BeautifulSoup(secondary_response.content, 'html.parser')
|
49 |
+
secondary_tables = secondary_soup.find_all('table')
|
50 |
+
|
51 |
+
for secondary_table in secondary_tables:
|
52 |
+
exam_booklet_links = secondary_table.find_all('a', title='Cuadernillo de Examen', href=True)
|
53 |
+
answer_sheet_links = secondary_table.find_all('a', title='Plantilla de respuestas', href=True)
|
54 |
+
|
55 |
+
for exam_booklet_link in exam_booklet_links:
|
56 |
+
pdf_url = exam_booklet_link['href']
|
57 |
+
if pdf_url.startswith('/'):
|
58 |
+
pdf_url = 'https://www.sspa.juntadeandalucia.es' + pdf_url
|
59 |
+
pdf_response = requests.get(pdf_url)
|
60 |
+
if pdf_response.status_code == 200:
|
61 |
+
file_path = os.path.join(folder_path, 'Exam_Booklet.pdf')
|
62 |
+
with open(file_path, 'wb') as pdf_file:
|
63 |
+
pdf_file.write(pdf_response.content)
|
64 |
+
print(f'Exam Booklet saved at: {file_path}')
|
65 |
+
|
66 |
+
for answer_sheet_link in answer_sheet_links:
|
67 |
+
pdf_url = answer_sheet_link['href']
|
68 |
+
if pdf_url.startswith('/'):
|
69 |
+
pdf_url = 'https://www.sspa.juntadeandalucia.es' + pdf_url
|
70 |
+
pdf_response = requests.get(pdf_url)
|
71 |
+
if pdf_response.status_code == 200:
|
72 |
+
file_path = os.path.join(folder_path, 'Answer_Sheet.pdf')
|
73 |
+
with open(file_path, 'wb') as pdf_file:
|
74 |
+
pdf_file.write(pdf_response.content)
|
75 |
+
print(f'Answer Sheet saved at: {file_path}')
|
76 |
+
|
77 |
+
else:
|
78 |
+
print(f'Error accessing the main page: {main_response.status_code}')
|
79 |
+
|
80 |
+
"""# Configure apikey"""
|
81 |
+
|
82 |
+
load_dotenv()
|
83 |
+
GEMINI_API_KEY = "AIzaSyB46xwQbdXC_TK3Wnl3kt-oXtqKN8dRYfI"
|
84 |
+
# TODO: PONER AQUI EL TOKEN
|
85 |
+
HF_TOKEN= ""
|
86 |
+
HF_DATASET_NAME="RafaelJaime/sas_opposition_exam_data"
|
87 |
+
|
88 |
+
"""# PDF processing
|
89 |
+
|
90 |
+
## Extract text
|
91 |
+
"""
|
92 |
+
|
93 |
+
def extract_text_from_pdf(pdf_path: str) -> str:
|
94 |
+
with open(pdf_path, "rb") as file:
|
95 |
+
reader = PyPDF2.PdfReader(file)
|
96 |
+
text = ""
|
97 |
+
for page in reader.pages:
|
98 |
+
text += page.extract_text()
|
99 |
+
return text
|
100 |
+
|
101 |
+
"""## Number of questions"""
|
102 |
+
|
103 |
+
import base64
|
104 |
+
import os
|
105 |
+
from google import genai
|
106 |
+
from google.genai import types
|
107 |
+
|
108 |
+
|
109 |
+
def generate_number_questions(text):
|
110 |
+
client = genai.Client(
|
111 |
+
api_key=GEMINI_API_KEY,
|
112 |
+
)
|
113 |
+
|
114 |
+
model = "gemini-2.0-flash"
|
115 |
+
contents = [
|
116 |
+
types.Content(
|
117 |
+
role="user",
|
118 |
+
parts=[
|
119 |
+
types.Part.from_text(text=f"""tell me how many questions you have in format {{"number": "numberofquestionsinteger"}} in the following text: {text}"""),
|
120 |
+
],
|
121 |
+
),
|
122 |
+
]
|
123 |
+
generate_content_config = types.GenerateContentConfig(
|
124 |
+
temperature=1,
|
125 |
+
top_p=0.95,
|
126 |
+
top_k=40,
|
127 |
+
max_output_tokens=8192,
|
128 |
+
response_mime_type="application/json",
|
129 |
+
)
|
130 |
+
response = client.models.generate_content(
|
131 |
+
model=model,
|
132 |
+
contents=contents,
|
133 |
+
config=generate_content_config,
|
134 |
+
)
|
135 |
+
|
136 |
+
return response.candidates[0].content.parts[0].text
|
137 |
+
|
138 |
+
"""## Process with llm"""
|
139 |
+
|
140 |
+
import json
|
141 |
+
import os
|
142 |
+
from google import genai
|
143 |
+
from google.genai import types
|
144 |
+
|
145 |
+
def process_with_gemini(text: str, start: int, end: int):
|
146 |
+
client = genai.Client(
|
147 |
+
api_key=GEMINI_API_KEY
|
148 |
+
)
|
149 |
+
|
150 |
+
model = "gemini-2.0-flash"
|
151 |
+
contents = [
|
152 |
+
types.Content(
|
153 |
+
role="user",
|
154 |
+
parts=[
|
155 |
+
types.Part.from_text(text=f"""
|
156 |
+
Given the following text of an exam with questions and answers, extract each question and its possible answers.
|
157 |
+
Format the output as a list of JSON with the following format, I want you to extract questions from {start} to {end}:
|
158 |
+
|
159 |
+
|
160 |
+
{{{{"question number in integer format": {{"statement": "question text", "answers": ["option A", "option B", ...]}}}}}}
|
161 |
+
|
162 |
+
Exam text:
|
163 |
+
{text}
|
164 |
+
"""),
|
165 |
+
],
|
166 |
+
),
|
167 |
+
]
|
168 |
+
|
169 |
+
generate_content_config = types.GenerateContentConfig(
|
170 |
+
temperature=1,
|
171 |
+
top_p=0.95,
|
172 |
+
top_k=40,
|
173 |
+
max_output_tokens=32768,
|
174 |
+
response_mime_type="application/json",
|
175 |
+
)
|
176 |
+
|
177 |
+
# Use generate_content() instead of streaming
|
178 |
+
response = client.models.generate_content(
|
179 |
+
model=model,
|
180 |
+
contents=contents,
|
181 |
+
config=generate_content_config,
|
182 |
+
)
|
183 |
+
|
184 |
+
return response.text # Return the response instead of printing it
|
185 |
+
|
186 |
+
"""# Collect the questions"""
|
187 |
+
|
188 |
+
import json
|
189 |
+
import os
|
190 |
+
from google import genai
|
191 |
+
from google.genai import types
|
192 |
+
|
193 |
+
def process_answers_with_gemini(text: str):
|
194 |
+
client = genai.Client(
|
195 |
+
api_key=GEMINI_API_KEY
|
196 |
+
)
|
197 |
+
|
198 |
+
model = "gemini-2.0-flash"
|
199 |
+
contents = [
|
200 |
+
types.Content(
|
201 |
+
role="user",
|
202 |
+
parts=[
|
203 |
+
types.Part.from_text(text=f"""
|
204 |
+
Please return the question number and the correct answers in format ['question number': 'answer letter','question number': 'answer letter'] from the following text
|
205 |
+
{text}
|
206 |
+
"""),
|
207 |
+
],
|
208 |
+
),
|
209 |
+
]
|
210 |
+
|
211 |
+
generate_content_config = types.GenerateContentConfig(
|
212 |
+
temperature=1,
|
213 |
+
top_p=0.95,
|
214 |
+
top_k=40,
|
215 |
+
max_output_tokens=32768,
|
216 |
+
response_mime_type="application/json",
|
217 |
+
)
|
218 |
+
|
219 |
+
# Use generate_content() instead of streaming
|
220 |
+
response = client.models.generate_content(
|
221 |
+
model=model,
|
222 |
+
contents=contents,
|
223 |
+
config=generate_content_config,
|
224 |
+
)
|
225 |
+
|
226 |
+
return response.text # Return the response instead of printing it
|
227 |
+
|
228 |
+
def process_pdf_file(pdf_path: str, answers_pdf_path: str, theme: str) -> pd.DataFrame:
|
229 |
+
pdf_text = extract_text_from_pdf(pdf_path)
|
230 |
+
result = generate_number_questions(pdf_text)
|
231 |
+
question_text = extract_text_from_pdf(answers_pdf_path)
|
232 |
+
|
233 |
+
# Process number of questions
|
234 |
+
try:
|
235 |
+
result_dict = json.loads(result)
|
236 |
+
except json.JSONDecodeError:
|
237 |
+
print("Error: The question count response is not valid JSON.")
|
238 |
+
return pd.DataFrame()
|
239 |
+
|
240 |
+
question_count = result_dict.get("number", "unknown")
|
241 |
+
print(f"The exam {pdf_path} contains {question_count} questions.")
|
242 |
+
|
243 |
+
try:
|
244 |
+
question_count = int(result_dict.get("number", 0))
|
245 |
+
except ValueError:
|
246 |
+
print(f"Error: Could not convert question count '{question_count}' to integer.")
|
247 |
+
return pd.DataFrame()
|
248 |
+
|
249 |
+
# Process questions in batches
|
250 |
+
questions = []
|
251 |
+
batch_size = 50
|
252 |
+
for start in range(1, question_count + 1, batch_size):
|
253 |
+
end = min(start + batch_size - 1, question_count)
|
254 |
+
print(f"Processing questions from {pdf_path} {start}-{end}...")
|
255 |
+
questions_subset = process_with_gemini(pdf_text, start, end)
|
256 |
+
questions.append(questions_subset)
|
257 |
+
|
258 |
+
|
259 |
+
# Combine all processed question batches
|
260 |
+
all_questions = []
|
261 |
+
for question_set in questions:
|
262 |
+
try:
|
263 |
+
question_list = json.loads(question_set)
|
264 |
+
all_questions.extend(question_list)
|
265 |
+
except json.JSONDecodeError:
|
266 |
+
print(f"Error: A question batch response is not valid JSON.")
|
267 |
+
continue
|
268 |
+
|
269 |
+
# If no valid questions were processed, return empty DataFrame
|
270 |
+
if not all_questions:
|
271 |
+
print("Error: No valid questions were processed.")
|
272 |
+
return pd.DataFrame()
|
273 |
+
|
274 |
+
# Process questions answers
|
275 |
+
questions_answer = process_answers_with_gemini(question_text)
|
276 |
+
try:
|
277 |
+
json_questions_answers = json.loads(questions_answer)
|
278 |
+
except json.JSONDecodeError:
|
279 |
+
print("Error: The response is not a valid JSON.")
|
280 |
+
|
281 |
+
# Format the data for the DataFrame
|
282 |
+
processed_data = []
|
283 |
+
for item in all_questions:
|
284 |
+
for key, value in item.items():
|
285 |
+
try:
|
286 |
+
real_answer = json_questions_answers[0].get(str(key), "Not available")
|
287 |
+
processed_data.append({
|
288 |
+
'id': key,
|
289 |
+
'statement': value['statement'],
|
290 |
+
'answers': value['answers'],
|
291 |
+
'real_answer': real_answer,
|
292 |
+
'theme': theme
|
293 |
+
})
|
294 |
+
except KeyError as e:
|
295 |
+
print(f"Error: Missing key in question data: {e}")
|
296 |
+
# Skip this question but continue with others
|
297 |
+
continue
|
298 |
+
|
299 |
+
# Create DataFrame from dictionary list
|
300 |
+
df = pd.DataFrame(processed_data)
|
301 |
+
if not df.empty:
|
302 |
+
df.set_index('id', inplace=True)
|
303 |
+
|
304 |
+
return df
|
305 |
+
|
306 |
+
|
307 |
+
all_df_array = []
|
308 |
+
# Verify that the folder exists
|
309 |
+
if os.path.exists(exams_folder):
|
310 |
+
for folder_name in os.listdir(exams_folder):
|
311 |
+
folder_path = os.path.join(exams_folder, folder_name)
|
312 |
+
|
313 |
+
# Verify that it's a folder
|
314 |
+
if os.path.isdir(folder_path):
|
315 |
+
print(f"Processing: {folder_name}")
|
316 |
+
|
317 |
+
files = os.listdir(folder_path)
|
318 |
+
|
319 |
+
# Initialize question and answer paths
|
320 |
+
questions_path = None
|
321 |
+
answers_path = None
|
322 |
+
|
323 |
+
# Look for files that start with the desired prefixes
|
324 |
+
for file in files:
|
325 |
+
if file.startswith('Exam_Booklet') and not questions_path:
|
326 |
+
questions_path = os.path.join(folder_path, file)
|
327 |
+
elif file.startswith('Answer_Sheet') and not answers_path:
|
328 |
+
answers_path = os.path.join(folder_path, file)
|
329 |
+
exam_df = process_pdf_file(questions_path, answers_path, folder_name)
|
330 |
+
if not exam_df.empty:
|
331 |
+
all_df_array.append(exam_df)
|
332 |
+
|
333 |
+
if all_df_array:
|
334 |
+
df = pd.concat(all_df_array, ignore_index=True) # `ignore_index=True` to avoid duplicates in the index
|
335 |
+
print(f"Final DataFrame with all questions and answers:\n{df}")
|
336 |
+
else:
|
337 |
+
print("No valid DataFrames were generated.")
|
338 |
+
|
339 |
+
"""# Upload to huggingface"""
|
340 |
+
|
341 |
+
login(HF_TOKEN)
|
342 |
+
Dataset.from_pandas(df).push_to_hub(HF_DATASET_NAME)
|