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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 02_data_augmentation.ipynb\n",
    "\n",
    "En este notebook realizamos las siguientes tareas:\n",
    "\n",
    "1. Cargamos y exploramos los datasets `wikidoc` y `medqa`.\n",
    "2. Unificamos o combinamos la información mínima necesaria.\n",
    "3. Generamos datos sintéticos (data augmentation) para enriquecer el conjunto.\n",
    "4. Realizamos pruebas llamando a las herramientas de triaje y asesoramiento.\n",
    "\n",
    "Al final, podemos convertir este notebook a un script `.py` si lo deseamos.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Importar librerías y configuraciones\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import random\n",
    "from pathlib import Path\n",
    "\n",
    "# Opcional: configuración para visualizar más columnas\n",
    "pd.set_option('display.max_columns', None)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Cargar y explorar datos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "===== wikidoc.info() =====\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 10000 entries, 0 to 9999\n",
      "Data columns (total 3 columns):\n",
      " #   Column       Non-Null Count  Dtype \n",
      "---  ------       --------------  ----- \n",
      " 0   instruction  10000 non-null  object\n",
      " 1   input        9998 non-null   object\n",
      " 2   output       10000 non-null  object\n",
      "dtypes: object(3)\n",
      "memory usage: 234.5+ KB\n",
      "\n",
      "===== wikidoc.head() =====\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>instruction</th>\n",
       "      <th>input</th>\n",
       "      <th>output</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Answer this question truthfully</td>\n",
       "      <td>Can you provide an overview of the lung's squa...</td>\n",
       "      <td>Squamous cell carcinoma of the lung may be cla...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Answer this question truthfully</td>\n",
       "      <td>What does \"Clear: cell\" mean?</td>\n",
       "      <td>Clear cell tumors are part of the surface epit...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Answer this question truthfully</td>\n",
       "      <td>Can you provide me with information regarding ...</td>\n",
       "      <td>Two Japanese scientists commenced research int...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Answer this question truthfully</td>\n",
       "      <td>What are the historical background and symptom...</td>\n",
       "      <td>Symptoms of vulvovaginitis caused by Candida s...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Answer this question truthfully</td>\n",
       "      <td>What does the \"Hypotension: Resident Survival ...</td>\n",
       "      <td>Hypotension is the term for low blood pressure...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       instruction  \\\n",
       "0  Answer this question truthfully   \n",
       "1  Answer this question truthfully   \n",
       "2  Answer this question truthfully   \n",
       "3  Answer this question truthfully   \n",
       "4  Answer this question truthfully   \n",
       "\n",
       "                                               input  \\\n",
       "0  Can you provide an overview of the lung's squa...   \n",
       "1                      What does \"Clear: cell\" mean?   \n",
       "2  Can you provide me with information regarding ...   \n",
       "3  What are the historical background and symptom...   \n",
       "4  What does the \"Hypotension: Resident Survival ...   \n",
       "\n",
       "                                              output  \n",
       "0  Squamous cell carcinoma of the lung may be cla...  \n",
       "1  Clear cell tumors are part of the surface epit...  \n",
       "2  Two Japanese scientists commenced research int...  \n",
       "3  Symptoms of vulvovaginitis caused by Candida s...  \n",
       "4  Hypotension is the term for low blood pressure...  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Ajusta la ruta según tu organización de carpetas\n",
    "raw_path = Path(\"../data/raw\")\n",
    "wikidoc_file = raw_path / \"medical_meadow_wikidoc.csv\"\n",
    "medqa_file = raw_path / \"medqa.csv\"\n",
    "\n",
    "wikidoc = pd.read_csv(wikidoc_file)\n",
    "medqa = pd.read_csv(medqa_file)\n",
    "\n",
    "print(\"===== wikidoc.info() =====\")\n",
    "wikidoc.info()\n",
    "print(\"\\n===== wikidoc.head() =====\")\n",
    "display(wikidoc.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "===== medqa.info() =====\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 10178 entries, 0 to 10177\n",
      "Data columns (total 6 columns):\n",
      " #   Column           Non-Null Count  Dtype \n",
      "---  ------           --------------  ----- \n",
      " 0   question         10178 non-null  object\n",
      " 1   answer           10177 non-null  object\n",
      " 2   options          10178 non-null  object\n",
      " 3   meta_info        10178 non-null  object\n",
      " 4   answer_idx       10178 non-null  object\n",
      " 5   metamap_phrases  10178 non-null  object\n",
      "dtypes: object(6)\n",
      "memory usage: 477.2+ KB\n",
      "\n",
      "===== medqa.head() =====\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>options</th>\n",
       "      <th>meta_info</th>\n",
       "      <th>answer_idx</th>\n",
       "      <th>metamap_phrases</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A 23-year-old pregnant woman at 22 weeks gesta...</td>\n",
       "      <td>Nitrofurantoin</td>\n",
       "      <td>{'A': 'Ampicillin', 'B': 'Ceftriaxone', 'C': '...</td>\n",
       "      <td>step2&amp;3</td>\n",
       "      <td>D</td>\n",
       "      <td>['23 year old pregnant woman', 'weeks presents...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>A 3-month-old baby died suddenly at night whil...</td>\n",
       "      <td>Placing the infant in a supine position on a f...</td>\n",
       "      <td>{'A': 'Placing the infant in a supine position...</td>\n",
       "      <td>step2&amp;3</td>\n",
       "      <td>A</td>\n",
       "      <td>['3 month old baby died', 'night', 'asleep', '...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>A mother brings her 3-week-old infant to the p...</td>\n",
       "      <td>Abnormal migration of ventral pancreatic bud</td>\n",
       "      <td>{'A': 'Abnormal migration of ventral pancreati...</td>\n",
       "      <td>step1</td>\n",
       "      <td>A</td>\n",
       "      <td>['mother', 'week old infant', \"pediatrician's ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>A pulmonary autopsy specimen from a 58-year-ol...</td>\n",
       "      <td>Thromboembolism</td>\n",
       "      <td>{'A': 'Thromboembolism', 'B': 'Pulmonary ische...</td>\n",
       "      <td>step1</td>\n",
       "      <td>A</td>\n",
       "      <td>['pulmonary autopsy specimen', '58 year old wo...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>A 20-year-old woman presents with menorrhagia ...</td>\n",
       "      <td>Von Willebrand disease</td>\n",
       "      <td>{'A': 'Hemophilia A', 'B': 'Lupus anticoagulan...</td>\n",
       "      <td>step1</td>\n",
       "      <td>D</td>\n",
       "      <td>['20 year old woman presents', 'menorrhagia', ...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                            question  \\\n",
       "0  A 23-year-old pregnant woman at 22 weeks gesta...   \n",
       "1  A 3-month-old baby died suddenly at night whil...   \n",
       "2  A mother brings her 3-week-old infant to the p...   \n",
       "3  A pulmonary autopsy specimen from a 58-year-ol...   \n",
       "4  A 20-year-old woman presents with menorrhagia ...   \n",
       "\n",
       "                                              answer  \\\n",
       "0                                     Nitrofurantoin   \n",
       "1  Placing the infant in a supine position on a f...   \n",
       "2       Abnormal migration of ventral pancreatic bud   \n",
       "3                                    Thromboembolism   \n",
       "4                             Von Willebrand disease   \n",
       "\n",
       "                                             options meta_info answer_idx  \\\n",
       "0  {'A': 'Ampicillin', 'B': 'Ceftriaxone', 'C': '...   step2&3          D   \n",
       "1  {'A': 'Placing the infant in a supine position...   step2&3          A   \n",
       "2  {'A': 'Abnormal migration of ventral pancreati...     step1          A   \n",
       "3  {'A': 'Thromboembolism', 'B': 'Pulmonary ische...     step1          A   \n",
       "4  {'A': 'Hemophilia A', 'B': 'Lupus anticoagulan...     step1          D   \n",
       "\n",
       "                                     metamap_phrases  \n",
       "0  ['23 year old pregnant woman', 'weeks presents...  \n",
       "1  ['3 month old baby died', 'night', 'asleep', '...  \n",
       "2  ['mother', 'week old infant', \"pediatrician's ...  \n",
       "3  ['pulmonary autopsy specimen', '58 year old wo...  \n",
       "4  ['20 year old woman presents', 'menorrhagia', ...  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "print(\"\\n===== medqa.info() =====\")\n",
    "medqa.info()\n",
    "print(\"\\n===== medqa.head() =====\")\n",
    "display(medqa.head())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (2686254339.py, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  Cell \u001b[1;32mIn[5], line 3\u001b[1;36m\u001b[0m\n\u001b[1;33m    Aquí podemos hacer una unificación mínima o simplemente quedarnos con columnas que nos interesen.\u001b[0m\n\u001b[1;37m         ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "## 3. Unificar o manipular datos\n",
    "\n",
    "Aquí podemos hacer una unificación mínima o simplemente quedarnos con columnas que nos interesen.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Copias de los dataframes\n",
    "df_wikidoc = wikidoc.copy()\n",
    "df_wikidoc.rename(columns={\"instruction\": \"consulta\", \"output\": \"respuesta\"}, inplace=True)\n",
    "\n",
    "# Un ejemplo: concatenar 'instruction' e 'input'\n",
    "df_wikidoc[\"consulta\"] = df_wikidoc[\"consulta\"].fillna(\"\") + \": \" + df_wikidoc[\"input\"].fillna(\"\")\n",
    "df_wikidoc = df_wikidoc[[\"consulta\", \"respuesta\"]]\n",
    "\n",
    "df_medqa = medqa.copy()\n",
    "df_medqa.rename(columns={\"question\": \"consulta\", \"answer\": \"respuesta\"}, inplace=True)\n",
    "\n",
    "# Unificación mínima\n",
    "df_unificado = pd.concat(\n",
    "    [df_wikidoc, df_medqa[[\"consulta\", \"respuesta\"]]],\n",
    "    ignore_index=True\n",
    ")\n",
    "\n",
    "# Eliminamos filas con NaN en consulta/respuesta\n",
    "df_unificado.dropna(subset=[\"consulta\", \"respuesta\"], inplace=True)\n",
    "\n",
    "print(\"Tamaño de df_unificado:\", df_unificado.shape)\n",
    "df_unificado.head()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Generación de Datos Sintéticos\n",
    "\n",
    "Definimos una función que toma ejemplos del dataframe unificado y genera variaciones.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generar_datos_sinteticos(df, n=10):\n",
    "    \"\"\"\n",
    "    Genera un conjunto de datos sintéticos basados en el dataframe unificado.\n",
    "    - Toma filas aleatorias de 'consulta' y 'respuesta'.\n",
    "    - Modifica ligeramente el texto para simular nuevas entradas.\n",
    "    \n",
    "    Retorna un DataFrame con las columnas 'consulta_sintetica' y 'respuesta_sintetica'.\n",
    "    \"\"\"\n",
    "    sampled_rows = df.sample(n, replace=True)\n",
    "\n",
    "    consultas_sinteticas = []\n",
    "    respuestas_sinteticas = []\n",
    "\n",
    "    modificaciones = [\n",
    "        \"(Por favor, detalle más los síntomas)\",\n",
    "        \"(Caso leve, pero podría complicarse)\",\n",
    "        \"(Consulta para un familiar)\",\n",
    "        \"(Síntomas descritos hace 2 días)\",\n",
    "        \"(Sugerir revisión médica)\"\n",
    "    ]\n",
    "\n",
    "    for _, row in sampled_rows.iterrows():\n",
    "        consulta_original = row[\"consulta\"]\n",
    "        respuesta_original = row[\"respuesta\"]\n",
    "\n",
    "        # Elegimos una modificación aleatoria\n",
    "        extra = random.choice(modificaciones)\n",
    "        nueva_consulta = f\"{consulta_original} {extra}\"\n",
    "\n",
    "        nueva_respuesta = (\n",
    "            respuesta_original\n",
    "            + \"\\nNota: Esta es una versión sintética para pruebas.\"\n",
    "        )\n",
    "\n",
    "        consultas_sinteticas.append(nueva_consulta)\n",
    "        respuestas_sinteticas.append(nueva_respuesta)\n",
    "\n",
    "    df_sintetico = pd.DataFrame({\n",
    "        \"consulta_sintetica\": consultas_sinteticas,\n",
    "        \"respuesta_sintetica\": respuestas_sinteticas\n",
    "    })\n",
    "\n",
    "    return df_sintetico\n",
    "\n",
    "# Generamos un ejemplo de datos sintéticos\n",
    "df_sintetico = generar_datos_sinteticos(df_unificado, n=15)\n",
    "print(\"Tamaño de df_sintetico:\", df_sintetico.shape)\n",
    "df_sintetico.head(10)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "carecompanion",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.21"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}