alezsd commited on
Commit
dc68f22
·
1 Parent(s): 0c5dff4

adaptacion JSON de Leo

Browse files
Files changed (2) hide show
  1. .gitignore +1 -0
  2. api_ner.py +94 -83
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ models/
api_ner.py CHANGED
@@ -2,17 +2,16 @@
2
  # coding: utf-8
3
  """
4
  FastAPI endpoint para el proyecto lanc-ner
5
- Recibe un archivo .txt y devuelve las anotaciones NER en formato JSON.
6
-
7
- Modelos disponibles:
8
- - ruler → models/model_entities_ruler/model-last/
9
- - toponyms → models/model_toponyms_patterns/model-last/
 
 
 
10
 
11
  Autenticación: Bearer token via variable de entorno API_TOKEN.
12
-
13
- Uso:
14
- export API_TOKEN="mi-token-secreto"
15
- uvicorn api_ner:app --host 0.0.0.0 --port 7860 --reload
16
  """
17
 
18
  from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Security, Query
@@ -21,7 +20,6 @@ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
21
  from fastapi.openapi.utils import get_openapi
22
  import spacy
23
  from spacy import displacy
24
- import pandas as pd
25
  import os
26
  import logging
27
 
@@ -57,9 +55,11 @@ app = FastAPI(
57
  "- `ruler` — Spacy Ruler (Sentences): entidades generales\n"
58
  "- `toponyms` — DECM annotations with Paragraphs: topónimos\n\n"
59
  "**Autenticación:** todos los endpoints de anotación requieren "
60
- "`Authorization: Bearer <token>` en la cabecera."
 
 
61
  ),
62
- version="1.2.0",
63
  docs_url="/docs",
64
  redoc_url="/redoc",
65
  )
@@ -78,37 +78,46 @@ def verify_token(credentials: HTTPAuthorizationCredentials = Security(bearer_sch
78
 
79
 
80
  # ── Función NER ───────────────────────────────────────────────────────────────
81
- def run_ner(text: str, model_name: str) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
82
  if model_name not in loaded_models:
83
- available = list(loaded_models.keys())
84
  raise HTTPException(
85
  status_code=400,
86
- detail=f"Modelo '{model_name}' no disponible. Opciones: {available}",
87
  )
88
 
89
  nlp = loaded_models[model_name]
90
- doc = nlp(text)
91
-
92
- # Entidades (igual que el DataFrame del código Streamlit)
93
- entities = [
94
- {
95
- "text": ent.text,
96
- "label": ent.label_,
97
- "start": ent.start_char,
98
- "end": ent.end_char,
99
- }
100
- for ent in doc.ents
101
- ]
102
 
103
- # Visualización HTML displaCy
104
- html = displacy.render(doc, style="ent", page=False, minify=True)
 
 
 
 
 
 
 
 
105
 
106
- return {
107
- "model": model_name,
108
- "num_entities": len(entities),
109
- "entities": entities,
110
- "html_visualization": html,
111
- }
112
 
113
 
114
  # ── Endpoints ─────────────────────────────────────────────────────────────────
@@ -128,7 +137,7 @@ def health_check():
128
  "/annotate",
129
  tags=["NER"],
130
  summary="Anotar documento .txt",
131
- response_description="Entidades NER detectadas y visualización HTML.",
132
  )
133
  async def annotate(
134
  file: UploadFile = File(..., description="Archivo de texto plano (.txt) a anotar."),
@@ -140,20 +149,24 @@ async def annotate(
140
  token: str = Depends(verify_token),
141
  ):
142
  """
143
- Recibe un archivo `.txt` y devuelve sus anotaciones NER.
144
 
145
  **Cabecera requerida:**
146
  ```
147
  Authorization: Bearer <tu-token>
148
  ```
149
 
150
- **Parámetro de query `model`:**
151
- - `ruler` (por defecto) — Spacy Ruler (Sentences)
152
- - `toponyms` — DECM annotations with Paragraphs
153
-
154
- **Ejemplo:**
155
- ```
156
- POST /annotate?model=toponyms
 
 
 
 
157
  ```
158
  """
159
  if not file.filename.lower().endswith(".txt"):
@@ -168,14 +181,14 @@ async def annotate(
168
  raise HTTPException(status_code=422, detail="El archivo está vacío.")
169
 
170
  result = run_ner(text, model)
171
- return JSONResponse(content={"filename": file.filename, **result})
172
 
173
 
174
  @app.post(
175
  "/annotate/text",
176
  tags=["NER"],
177
  summary="Anotar texto plano (JSON)",
178
- response_description="Entidades NER detectadas y visualización HTML.",
179
  )
180
  async def annotate_text(
181
  payload: dict,
@@ -263,51 +276,38 @@ def docu():
263
  <title>{app.title} — Documentación</title>
264
  <style>
265
  *, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; }}
266
- body {{ font-family: 'Segoe UI', system-ui, sans-serif; background: #f5f7fa;
267
- color: #1a1a2e; line-height: 1.6; }}
268
- header {{ background: linear-gradient(135deg,#1a1a2e,#16213e);
269
- color:#fff; padding: 2.5rem 2rem; }}
270
  header h1 {{ font-size: 2rem; margin-bottom:.4rem; }}
271
  header p {{ opacity:.8; font-size:1rem; }}
272
- .version {{ display:inline-block; background:#e94560; color:#fff;
273
- font-size:.75rem; padding:.2rem .6rem; border-radius:12px;
274
- margin-left:.6rem; vertical-align:middle; }}
275
  main {{ max-width: 860px; margin: 2rem auto; padding: 0 1rem 4rem; }}
276
  section {{ margin-bottom: 2.5rem; }}
277
- h2 {{ font-size: 1.25rem; border-bottom: 2px solid #e94560;
278
- padding-bottom:.4rem; margin-bottom:1rem; color:#16213e; }}
279
- .auth-box {{ background:#fff3cd; border-left:4px solid #ffc107;
280
- padding:1rem 1.2rem; border-radius:6px; margin-bottom:1.5rem; }}
281
  .auth-box code {{ background:#ffe69c; padding:.1rem .4rem; border-radius:3px; }}
282
- .model-box {{ background:#e8f4fd; border-left:4px solid #61affe;
283
- padding:1rem 1.2rem; border-radius:6px; margin-bottom:1.5rem; }}
284
  .model-box code {{ background:#cce5ff; padding:.1rem .4rem; border-radius:3px; }}
285
- .endpoint {{ background:#fff; border:1px solid #e0e4ef; border-radius:8px;
286
- padding:1.2rem 1.4rem; margin-bottom:1rem;
287
- box-shadow:0 1px 4px rgba(0,0,0,.06); }}
288
- .ep-header {{ display:flex; align-items:center; gap:.8rem; flex-wrap:wrap;
289
- margin-bottom:.5rem; }}
290
- .badge {{ color:#fff; font-size:.7rem; font-weight:700; padding:.25rem .6rem;
291
- border-radius:4px; letter-spacing:.05em; }}
292
  .ep-path {{ font-family:monospace; font-size:1rem; font-weight:600; }}
293
  .ep-summary {{ color:#555; font-size:.9rem; }}
294
  .ep-desc {{ color:#444; font-size:.9rem; margin-bottom:.6rem; }}
295
  .param-table {{ width:100%; border-collapse:collapse; font-size:.85rem; margin-top:.5rem; }}
296
- .param-table th {{ background:#f0f2f8; text-align:left;
297
- padding:.4rem .6rem; border:1px solid #dde; }}
298
  .param-table td {{ padding:.4rem .6rem; border:1px solid #eef; }}
299
- pre {{ background:#1e2235; color:#cdd6f4; padding:1rem; border-radius:6px;
300
- overflow-x:auto; font-size:.85rem; margin-top:.5rem; }}
301
  .links {{ display:flex; gap:1rem; flex-wrap:wrap; }}
302
- .links a {{ display:inline-block; background:#16213e; color:#fff; text-decoration:none;
303
- padding:.5rem 1.1rem; border-radius:6px; font-size:.9rem; }}
304
  .links a:hover {{ background:#e94560; }}
305
  </style>
306
  </head>
307
  <body>
308
  <header>
309
  <h1>{app.title} <span class="version">v{app.version}</span></h1>
310
- <p>Detección de entidades nombradas (NER) sobre documentos de texto en español.</p>
311
  </header>
312
  <main>
313
 
@@ -319,6 +319,24 @@ def docu():
319
  </div>
320
  </section>
321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  <section>
323
  <h2>Modelos disponibles</h2>
324
  <div class="model-box">
@@ -328,15 +346,13 @@ def docu():
328
  <p><code>toponyms</code> — <strong>DECM annotations with Paragraphs</strong><br/>
329
  Especializado en topónimos y anotaciones geográficas por párrafos.</p>
330
  </div>
331
- Selecciona el modelo con el parámetro de query: <code>?model=ruler</code> o <code>?model=toponyms</code>
332
  </section>
333
 
334
  <section>
335
  <h2>Autenticación</h2>
336
  <div class="auth-box">
337
  Todos los endpoints de anotación requieren un <strong>Bearer token</strong>:<br/><br/>
338
- <code>Authorization: Bearer &lt;tu-token&gt;</code><br/><br/>
339
- Configurado mediante la variable de entorno <code>API_TOKEN</code> en HF Spaces.
340
  </div>
341
  </section>
342
 
@@ -347,18 +363,13 @@ def docu():
347
 
348
  <section>
349
  <h2>Ejemplos de uso</h2>
350
- <p><strong>Subir archivo .txt (modelo ruler):</strong></p>
351
  <pre>curl -X POST "https://alezsd-lancaster-ner-api.hf.space/annotate?model=ruler" \\
352
  -H "Authorization: Bearer &lt;token&gt;" \\
353
  -F "file=@documento.txt"</pre>
354
 
355
- <p style="margin-top:1rem"><strong>Subir archivo .txt (modelo toponyms):</strong></p>
356
- <pre>curl -X POST "https://alezsd-lancaster-ner-api.hf.space/annotate?model=toponyms" \\
357
- -H "Authorization: Bearer &lt;token&gt;" \\
358
- -F "file=@documento.txt"</pre>
359
-
360
  <p style="margin-top:1rem"><strong>Enviar texto como JSON:</strong></p>
361
- <pre>curl -X POST "https://alezsd-lancaster-ner-api.hf.space/annotate/text?model=ruler" \\
362
  -H "Authorization: Bearer &lt;token&gt;" \\
363
  -H "Content-Type: application/json" \\
364
  -d '{{"text": "El municipio de Atengo se encuentra en Jalisco."}}'</pre>
 
2
  # coding: utf-8
3
  """
4
  FastAPI endpoint para el proyecto lanc-ner
5
+ Recibe un archivo .txt y devuelve las anotaciones NER en formato JSON
6
+ por línea, con el esquema:
7
+ [
8
+ { "Anotacion": "<línea>", "entities": [
9
+ { "start": int, "end": int, "entity": str, "fields": [str] }
10
+ ]},
11
+ ...
12
+ ]
13
 
14
  Autenticación: Bearer token via variable de entorno API_TOKEN.
 
 
 
 
15
  """
16
 
17
  from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Security, Query
 
20
  from fastapi.openapi.utils import get_openapi
21
  import spacy
22
  from spacy import displacy
 
23
  import os
24
  import logging
25
 
 
55
  "- `ruler` — Spacy Ruler (Sentences): entidades generales\n"
56
  "- `toponyms` — DECM annotations with Paragraphs: topónimos\n\n"
57
  "**Autenticación:** todos los endpoints de anotación requieren "
58
+ "`Authorization: Bearer <token>` en la cabecera.\n\n"
59
+ "**Formato de salida:** lista de objetos por línea del documento, "
60
+ "con campo `Anotacion` (texto de la línea) y `entities` (entidades detectadas)."
61
  ),
62
+ version="1.3.0",
63
  docs_url="/docs",
64
  redoc_url="/redoc",
65
  )
 
78
 
79
 
80
  # ── Función NER ───────────────────────────────────────────────────────────────
81
+ def run_ner(text: str, model_name: str) -> list:
82
+ """
83
+ Procesa el texto línea a línea y devuelve una lista con el formato:
84
+ [
85
+ {
86
+ "Anotacion": "<línea>",
87
+ "entities": [
88
+ { "start": int, "end": int, "entity": str, "fields": [str] }
89
+ ]
90
+ },
91
+ ...
92
+ ]
93
+ """
94
  if model_name not in loaded_models:
 
95
  raise HTTPException(
96
  status_code=400,
97
+ detail=f"Modelo '{model_name}' no disponible. Opciones: {list(loaded_models.keys())}",
98
  )
99
 
100
  nlp = loaded_models[model_name]
101
+ lines = text.splitlines()
102
+ result = []
 
 
 
 
 
 
 
 
 
 
103
 
104
+ for line in lines:
105
+ doc = nlp(line)
106
+ entities = []
107
+ for ent in doc.ents:
108
+ entities.append({
109
+ "start": ent.start_char,
110
+ "end": ent.end_char,
111
+ "entity": ent.label_,
112
+ "fields": [],
113
+ })
114
 
115
+ result.append({
116
+ "Anotacion": line,
117
+ "entities": entities,
118
+ })
119
+
120
+ return result
121
 
122
 
123
  # ── Endpoints ─────────────────────────────────────────────────────────────────
 
137
  "/annotate",
138
  tags=["NER"],
139
  summary="Anotar documento .txt",
140
+ response_description="Lista de anotaciones NER por línea del documento.",
141
  )
142
  async def annotate(
143
  file: UploadFile = File(..., description="Archivo de texto plano (.txt) a anotar."),
 
149
  token: str = Depends(verify_token),
150
  ):
151
  """
152
+ Recibe un archivo `.txt` y devuelve una lista de anotaciones NER por línea.
153
 
154
  **Cabecera requerida:**
155
  ```
156
  Authorization: Bearer <tu-token>
157
  ```
158
 
159
+ **Formato de respuesta:**
160
+ ```json
161
+ [
162
+ {
163
+ "Anotacion": "Registraron Baltasar Perez y Ernando de Sanctiago vesinos de Sevilla",
164
+ "entities": [
165
+ { "start": 12, "end": 26, "entity": "Persona", "fields": ["Nombre", "Hombre"] },
166
+ { "start": 61, "end": 68, "entity": "Localización", "fields": ["Topónimo"] }
167
+ ]
168
+ }
169
+ ]
170
  ```
171
  """
172
  if not file.filename.lower().endswith(".txt"):
 
181
  raise HTTPException(status_code=422, detail="El archivo está vacío.")
182
 
183
  result = run_ner(text, model)
184
+ return JSONResponse(content=result)
185
 
186
 
187
  @app.post(
188
  "/annotate/text",
189
  tags=["NER"],
190
  summary="Anotar texto plano (JSON)",
191
+ response_description="Lista de anotaciones NER por línea.",
192
  )
193
  async def annotate_text(
194
  payload: dict,
 
276
  <title>{app.title} — Documentación</title>
277
  <style>
278
  *, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; }}
279
+ body {{ font-family: 'Segoe UI', system-ui, sans-serif; background: #f5f7fa; color: #1a1a2e; line-height: 1.6; }}
280
+ header {{ background: linear-gradient(135deg,#1a1a2e,#16213e); color:#fff; padding: 2.5rem 2rem; }}
 
 
281
  header h1 {{ font-size: 2rem; margin-bottom:.4rem; }}
282
  header p {{ opacity:.8; font-size:1rem; }}
283
+ .version {{ display:inline-block; background:#e94560; color:#fff; font-size:.75rem; padding:.2rem .6rem; border-radius:12px; margin-left:.6rem; vertical-align:middle; }}
 
 
284
  main {{ max-width: 860px; margin: 2rem auto; padding: 0 1rem 4rem; }}
285
  section {{ margin-bottom: 2.5rem; }}
286
+ h2 {{ font-size: 1.25rem; border-bottom: 2px solid #e94560; padding-bottom:.4rem; margin-bottom:1rem; color:#16213e; }}
287
+ .auth-box {{ background:#fff3cd; border-left:4px solid #ffc107; padding:1rem 1.2rem; border-radius:6px; margin-bottom:1.5rem; }}
 
 
288
  .auth-box code {{ background:#ffe69c; padding:.1rem .4rem; border-radius:3px; }}
289
+ .model-box {{ background:#e8f4fd; border-left:4px solid #61affe; padding:1rem 1.2rem; border-radius:6px; margin-bottom:1rem; }}
 
290
  .model-box code {{ background:#cce5ff; padding:.1rem .4rem; border-radius:3px; }}
291
+ .format-box {{ background:#f0fff4; border-left:4px solid #49cc90; padding:1rem 1.2rem; border-radius:6px; margin-bottom:1rem; }}
292
+ .endpoint {{ background:#fff; border:1px solid #e0e4ef; border-radius:8px; padding:1.2rem 1.4rem; margin-bottom:1rem; box-shadow:0 1px 4px rgba(0,0,0,.06); }}
293
+ .ep-header {{ display:flex; align-items:center; gap:.8rem; flex-wrap:wrap; margin-bottom:.5rem; }}
294
+ .badge {{ color:#fff; font-size:.7rem; font-weight:700; padding:.25rem .6rem; border-radius:4px; letter-spacing:.05em; }}
 
 
 
295
  .ep-path {{ font-family:monospace; font-size:1rem; font-weight:600; }}
296
  .ep-summary {{ color:#555; font-size:.9rem; }}
297
  .ep-desc {{ color:#444; font-size:.9rem; margin-bottom:.6rem; }}
298
  .param-table {{ width:100%; border-collapse:collapse; font-size:.85rem; margin-top:.5rem; }}
299
+ .param-table th {{ background:#f0f2f8; text-align:left; padding:.4rem .6rem; border:1px solid #dde; }}
 
300
  .param-table td {{ padding:.4rem .6rem; border:1px solid #eef; }}
301
+ pre {{ background:#1e2235; color:#cdd6f4; padding:1rem; border-radius:6px; overflow-x:auto; font-size:.85rem; margin-top:.5rem; }}
 
302
  .links {{ display:flex; gap:1rem; flex-wrap:wrap; }}
303
+ .links a {{ display:inline-block; background:#16213e; color:#fff; text-decoration:none; padding:.5rem 1.1rem; border-radius:6px; font-size:.9rem; }}
 
304
  .links a:hover {{ background:#e94560; }}
305
  </style>
306
  </head>
307
  <body>
308
  <header>
309
  <h1>{app.title} <span class="version">v{app.version}</span></h1>
310
+ <p>Detección de entidades nombradas (NER) sobre documentos de texto históricos.</p>
311
  </header>
312
  <main>
313
 
 
319
  </div>
320
  </section>
321
 
322
+ <section>
323
+ <h2>Formato de respuesta</h2>
324
+ <div class="format-box">
325
+ El documento se procesa <strong>línea a línea</strong>. Cada línea genera un objeto con:<br/><br/>
326
+ <code>Anotacion</code> — texto original de la línea<br/>
327
+ <code>entities</code> — lista de entidades detectadas con <code>start</code>, <code>end</code>, <code>entity</code> y <code>fields</code>
328
+ </div>
329
+ <pre>[
330
+ {{
331
+ "Anotacion": "Registraron Baltasar Perez y Ernando de Sanctiago vesinos de Sevilla",
332
+ "entities": [
333
+ {{ "start": 12, "end": 26, "entity": "Persona", "fields": ["Nombre", "Hombre"] }},
334
+ {{ "start": 61, "end": 68, "entity": "Localización", "fields": ["Topónimo"] }}
335
+ ]
336
+ }}
337
+ ]</pre>
338
+ </section>
339
+
340
  <section>
341
  <h2>Modelos disponibles</h2>
342
  <div class="model-box">
 
346
  <p><code>toponyms</code> — <strong>DECM annotations with Paragraphs</strong><br/>
347
  Especializado en topónimos y anotaciones geográficas por párrafos.</p>
348
  </div>
 
349
  </section>
350
 
351
  <section>
352
  <h2>Autenticación</h2>
353
  <div class="auth-box">
354
  Todos los endpoints de anotación requieren un <strong>Bearer token</strong>:<br/><br/>
355
+ <code>Authorization: Bearer &lt;tu-token&gt;</code>
 
356
  </div>
357
  </section>
358
 
 
363
 
364
  <section>
365
  <h2>Ejemplos de uso</h2>
366
+ <p><strong>Subir archivo .txt:</strong></p>
367
  <pre>curl -X POST "https://alezsd-lancaster-ner-api.hf.space/annotate?model=ruler" \\
368
  -H "Authorization: Bearer &lt;token&gt;" \\
369
  -F "file=@documento.txt"</pre>
370
 
 
 
 
 
 
371
  <p style="margin-top:1rem"><strong>Enviar texto como JSON:</strong></p>
372
+ <pre>curl -X POST "https://alezsd-lancaster-ner-api.hf.space/annotate/text?model=toponyms" \\
373
  -H "Authorization: Bearer &lt;token&gt;" \\
374
  -H "Content-Type: application/json" \\
375
  -d '{{"text": "El municipio de Atengo se encuentra en Jalisco."}}'</pre>