alezsd commited on
Commit
f6ff684
·
1 Parent(s): dfe1a49

models updated

Browse files
Files changed (4) hide show
  1. .DS_Store +0 -0
  2. Dockerfile +4 -9
  3. api_ner.py +98 -102
  4. requirements.txt +3 -1
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
Dockerfile CHANGED
@@ -1,28 +1,23 @@
1
- # ── Imagen base ───────────────────────────────────────────────────────────────
2
  FROM python:3.10-slim
3
 
4
- # HF Spaces expone el puerto 7860
5
  ENV PORT=7860
6
- ENV NER_MODEL=en_core_web_sm
7
 
8
  WORKDIR /app
9
 
10
- # ── Dependencias del sistema ───────────────────────────────────────────────────
11
  RUN apt-get update && apt-get install -y --no-install-recommends \
12
  build-essential \
13
  curl \
14
  && rm -rf /var/lib/apt/lists/*
15
 
16
- # ── Dependencias Python ────────────────────────────────────────────────────────
17
  COPY requirements.txt .
18
  RUN pip install --no-cache-dir -r requirements.txt
19
 
20
- # ── Modelo spaCy ──────────────────────────────────────────────────────────────
21
- RUN python -m spacy download en_core_web_sm
22
 
23
- # ── Código de la app ──────────────────────────────────────────────────────────
24
  COPY api_ner.py .
25
 
26
  EXPOSE 7860
27
 
28
- CMD ["uvicorn", "api_ner:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
1
  FROM python:3.10-slim
2
 
 
3
  ENV PORT=7860
 
4
 
5
  WORKDIR /app
6
 
 
7
  RUN apt-get update && apt-get install -y --no-install-recommends \
8
  build-essential \
9
  curl \
10
  && rm -rf /var/lib/apt/lists/*
11
 
 
12
  COPY requirements.txt .
13
  RUN pip install --no-cache-dir -r requirements.txt
14
 
15
+ # Copia los modelos entrenados propios
16
+ COPY models/ ./models/
17
 
18
+ # Copia el código de la API
19
  COPY api_ner.py .
20
 
21
  EXPOSE 7860
22
 
23
+ CMD ["uvicorn", "api_ner:app", "--host", "0.0.0.0", "--port", "7860"]
api_ner.py CHANGED
@@ -4,6 +4,10 @@
4
  FastAPI endpoint para el proyecto lanc-ner
5
  Recibe un archivo .txt y devuelve las anotaciones NER en formato JSON.
6
 
 
 
 
 
7
  Autenticación: Bearer token via variable de entorno API_TOKEN.
8
 
9
  Uso:
@@ -11,12 +15,13 @@ Uso:
11
  uvicorn api_ner:app --host 0.0.0.0 --port 7860 --reload
12
  """
13
 
14
- from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Security
15
  from fastapi.responses import JSONResponse, HTMLResponse
16
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
17
  from fastapi.openapi.utils import get_openapi
18
  import spacy
19
  from spacy import displacy
 
20
  import os
21
  import logging
22
 
@@ -25,40 +30,44 @@ logging.basicConfig(level=logging.INFO)
25
  logger = logging.getLogger(__name__)
26
 
27
  # ── Configuración ─────────────────────────────────────────────────────────────
28
- NLP_MODEL_PATH = os.getenv("NER_MODEL", "en_core_web_sm")
29
- API_TOKEN = os.getenv("API_TOKEN", "") # obligatorio en producción
30
-
31
  if not API_TOKEN:
32
  logger.warning("⚠️ API_TOKEN no definido — la API está desprotegida.")
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  # ── App ───────────────────────────────────────────────────────────────────────
35
  app = FastAPI(
36
  title="Lancaster NER API",
37
  description=(
38
  "API REST para detección de entidades nombradas (NER) basada en spaCy.\n\n"
39
- "**Autenticación:** todos los endpoints protegidos requieren un "
40
- "`Authorization: Bearer <token>` en la cabecera.\n\n"
41
- "Consulta `/docs` para la documentación interactiva (Swagger UI) "
42
- "o `/redoc` para la versión ReDoc."
 
43
  ),
44
- version="1.1.0",
45
  docs_url="/docs",
46
  redoc_url="/redoc",
47
  )
48
 
49
- # ── Modelo spaCy ──────────────────────────────────────────────────────────────
50
- try:
51
- nlp = spacy.load(NLP_MODEL_PATH)
52
- logger.info(f"Modelo cargado: {NLP_MODEL_PATH}")
53
- except OSError:
54
- logger.error(f"Modelo '{NLP_MODEL_PATH}' no encontrado.")
55
- nlp = None
56
-
57
  # ── Seguridad: Bearer token ───────────────────────────────────────────────────
58
  bearer_scheme = HTTPBearer(auto_error=True)
59
 
60
  def verify_token(credentials: HTTPAuthorizationCredentials = Security(bearer_scheme)):
61
- """Valida el Bearer token contra la variable de entorno API_TOKEN."""
62
  if API_TOKEN and credentials.credentials != API_TOKEN:
63
  raise HTTPException(
64
  status_code=401,
@@ -69,63 +78,49 @@ def verify_token(credentials: HTTPAuthorizationCredentials = Security(bearer_sch
69
 
70
 
71
  # ── Función NER ───────────────────────────────────────────────────────────────
72
- def run_ner(text: str) -> dict:
73
- if nlp is None:
74
- raise RuntimeError("El modelo NLP no está disponible.")
 
 
 
 
75
 
 
76
  doc = nlp(text)
77
 
 
78
  entities = [
79
  {
80
- "text": ent.text,
81
  "label": ent.label_,
82
- "label_description": spacy.explain(ent.label_) or "",
83
  "start": ent.start_char,
84
- "end": ent.end_char,
85
  }
86
  for ent in doc.ents
87
  ]
88
 
89
- tokens = [
90
- {
91
- "token": token.text,
92
- "pos": token.pos_,
93
- "tag": token.tag_,
94
- "dep": token.dep_,
95
- "ent_iob": token.ent_iob_,
96
- "ent_type": token.ent_type_,
97
- }
98
- for token in doc
99
- ]
100
-
101
  html = displacy.render(doc, style="ent", page=False, minify=True)
102
 
103
  return {
104
- "num_entities": len(entities),
105
- "entities": entities,
106
- "tokens": tokens,
107
  "html_visualization": html,
108
  }
109
 
110
 
111
  # ── Endpoints ─────────────────────────────────────────────────────────────────
112
 
113
- @app.get(
114
- "/",
115
- tags=["Health"],
116
- summary="Health check",
117
- response_description="Estado de la API y del modelo cargado.",
118
- )
119
  def health_check():
120
- """
121
- Comprueba que la API está en marcha.
122
- **No requiere autenticación.**
123
- """
124
  return {
125
  "status": "ok",
126
- "model": NLP_MODEL_PATH,
127
- "model_status": "loaded" if nlp is not None else "not loaded",
128
  "auth_enabled": bool(API_TOKEN),
 
 
129
  }
130
 
131
 
@@ -133,10 +128,15 @@ def health_check():
133
  "/annotate",
134
  tags=["NER"],
135
  summary="Anotar documento .txt",
136
- response_description="Entidades NER detectadas, tokens y visualización HTML.",
137
  )
138
  async def annotate(
139
  file: UploadFile = File(..., description="Archivo de texto plano (.txt) a anotar."),
 
 
 
 
 
140
  token: str = Depends(verify_token),
141
  ):
142
  """
@@ -147,23 +147,13 @@ async def annotate(
147
  Authorization: Bearer <tu-token>
148
  ```
149
 
150
- **Respuesta:**
151
- ```json
152
- {
153
- "filename": "documento.txt",
154
- "num_entities": 2,
155
- "entities": [
156
- {
157
- "text": "London",
158
- "label": "GPE",
159
- "label_description": "Countries, cities, states",
160
- "start": 5,
161
- "end": 11
162
- }
163
- ],
164
- "tokens": [...],
165
- "html_visualization": "<div>...</div>"
166
- }
167
  ```
168
  """
169
  if not file.filename.lower().endswith(".txt"):
@@ -177,11 +167,7 @@ async def annotate(
177
  if not text.strip():
178
  raise HTTPException(status_code=422, detail="El archivo está vacío.")
179
 
180
- try:
181
- result = run_ner(text)
182
- except RuntimeError as e:
183
- raise HTTPException(status_code=503, detail=str(e))
184
-
185
  return JSONResponse(content={"filename": file.filename, **result})
186
 
187
 
@@ -189,34 +175,30 @@ async def annotate(
189
  "/annotate/text",
190
  tags=["NER"],
191
  summary="Anotar texto plano (JSON)",
192
- response_description="Entidades NER detectadas, tokens y visualización HTML.",
193
  )
194
  async def annotate_text(
195
  payload: dict,
 
 
 
 
 
196
  token: str = Depends(verify_token),
197
  ):
198
  """
199
- Alternativa a `/annotate`: envía el texto directamente en el body JSON.
200
-
201
- **Cabecera requerida:**
202
- ```
203
- Authorization: Bearer <tu-token>
204
- ```
205
 
206
  **Body:**
207
  ```json
208
- { "text": "John lives in New York." }
209
  ```
210
  """
211
  text = payload.get("text", "").strip()
212
  if not text:
213
  raise HTTPException(status_code=422, detail="El campo 'text' está vacío.")
214
 
215
- try:
216
- result = run_ner(text)
217
- except RuntimeError as e:
218
- raise HTTPException(status_code=503, detail=str(e))
219
-
220
  return JSONResponse(content=result)
221
 
222
 
@@ -225,14 +207,10 @@ async def annotate_text(
225
  tags=["Documentación"],
226
  summary="Documentación HTML del servicio",
227
  response_class=HTMLResponse,
228
- include_in_schema=False, # no aparece en /docs para no duplicar
229
  )
230
  def docu():
231
- """
232
- Página HTML autodocumentada con la descripción completa del servicio,
233
- sus endpoints, parámetros y ejemplos de uso.
234
- **No requiere autenticación.**
235
- """
236
  schema = get_openapi(
237
  title=app.title,
238
  version=app.version,
@@ -301,6 +279,9 @@ def docu():
301
  .auth-box {{ background:#fff3cd; border-left:4px solid #ffc107;
302
  padding:1rem 1.2rem; border-radius:6px; margin-bottom:1.5rem; }}
303
  .auth-box code {{ background:#ffe69c; padding:.1rem .4rem; border-radius:3px; }}
 
 
 
304
  .endpoint {{ background:#fff; border:1px solid #e0e4ef; border-radius:8px;
305
  padding:1.2rem 1.4rem; margin-bottom:1rem;
306
  box-shadow:0 1px 4px rgba(0,0,0,.06); }}
@@ -326,7 +307,7 @@ def docu():
326
  <body>
327
  <header>
328
  <h1>{app.title} <span class="version">v{app.version}</span></h1>
329
- <p>Detección de entidades nombradas (NER) sobre documentos de texto.</p>
330
  </header>
331
  <main>
332
 
@@ -338,14 +319,24 @@ def docu():
338
  </div>
339
  </section>
340
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  <section>
342
  <h2>Autenticación</h2>
343
  <div class="auth-box">
344
- Todos los endpoints de anotación requieren un <strong>Bearer token</strong>
345
- en la cabecera HTTP:<br/><br/>
346
  <code>Authorization: Bearer &lt;tu-token&gt;</code><br/><br/>
347
- El token se configura mediante la variable de entorno <code>API_TOKEN</code>
348
- en el Space de Hugging Face.
349
  </div>
350
  </section>
351
 
@@ -356,16 +347,21 @@ def docu():
356
 
357
  <section>
358
  <h2>Ejemplos de uso</h2>
359
- <p><strong>Subir archivo .txt:</strong></p>
360
- <pre>curl -X POST "https://&lt;space&gt;.hf.space/annotate" \\
 
 
 
 
 
361
  -H "Authorization: Bearer &lt;token&gt;" \\
362
  -F "file=@documento.txt"</pre>
363
 
364
  <p style="margin-top:1rem"><strong>Enviar texto como JSON:</strong></p>
365
- <pre>curl -X POST "https://&lt;space&gt;.hf.space/annotate/text" \\
366
  -H "Authorization: Bearer &lt;token&gt;" \\
367
  -H "Content-Type: application/json" \\
368
- -d '{{"text": "John lives in New York."}}'</pre>
369
  </section>
370
 
371
  </main>
 
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:
 
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
19
  from fastapi.responses import JSONResponse, HTMLResponse
20
  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
 
 
30
  logger = logging.getLogger(__name__)
31
 
32
  # ── Configuración ─────────────────────────────────────────────────────────────
33
+ API_TOKEN = os.getenv("API_TOKEN", "")
 
 
34
  if not API_TOKEN:
35
  logger.warning("⚠️ API_TOKEN no definido — la API está desprotegida.")
36
 
37
+ MODELS = {
38
+ "ruler": "./models/model_entities_ruler/model-last/",
39
+ "toponyms": "./models/model_toponyms_patterns/model-last/",
40
+ }
41
+
42
+ # ── Carga de modelos ──────────────────────────────────────────────────────────
43
+ loaded_models = {}
44
+ for name, path in MODELS.items():
45
+ try:
46
+ loaded_models[name] = spacy.load(path)
47
+ logger.info(f"Modelo '{name}' cargado desde {path}")
48
+ except OSError:
49
+ logger.error(f"Modelo '{name}' no encontrado en {path}")
50
+
51
  # ── App ───────────────────────────────────────────────────────────────────────
52
  app = FastAPI(
53
  title="Lancaster NER API",
54
  description=(
55
  "API REST para detección de entidades nombradas (NER) basada en spaCy.\n\n"
56
+ "**Modelos disponibles:**\n"
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
  )
66
 
 
 
 
 
 
 
 
 
67
  # ── Seguridad: Bearer token ───────────────────────────────────────────────────
68
  bearer_scheme = HTTPBearer(auto_error=True)
69
 
70
  def verify_token(credentials: HTTPAuthorizationCredentials = Security(bearer_scheme)):
 
71
  if API_TOKEN and credentials.credentials != API_TOKEN:
72
  raise HTTPException(
73
  status_code=401,
 
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 ─────────────────────────────────────────────────────────────────
115
 
116
+ @app.get("/", tags=["Health"], summary="Health check")
 
 
 
 
 
117
  def health_check():
118
+ """Estado de la API y modelos cargados. **No requiere autenticación.**"""
 
 
 
119
  return {
120
  "status": "ok",
 
 
121
  "auth_enabled": bool(API_TOKEN),
122
+ "models_available": list(loaded_models.keys()),
123
+ "models_missing": [k for k in MODELS if k not in loaded_models],
124
  }
125
 
126
 
 
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."),
135
+ model: str = Query(
136
+ default="ruler",
137
+ description="Modelo NER a usar: `ruler` o `toponyms`.",
138
+ enum=["ruler", "toponyms"],
139
+ ),
140
  token: str = Depends(verify_token),
141
  ):
142
  """
 
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"):
 
167
  if not text.strip():
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
 
 
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,
182
+ model: str = Query(
183
+ default="ruler",
184
+ description="Modelo NER a usar: `ruler` o `toponyms`.",
185
+ enum=["ruler", "toponyms"],
186
+ ),
187
  token: str = Depends(verify_token),
188
  ):
189
  """
190
+ Envía el texto directamente en el body JSON.
 
 
 
 
 
191
 
192
  **Body:**
193
  ```json
194
+ { "text": "El municipio de Atengo se encuentra en Jalisco." }
195
  ```
196
  """
197
  text = payload.get("text", "").strip()
198
  if not text:
199
  raise HTTPException(status_code=422, detail="El campo 'text' está vacío.")
200
 
201
+ result = run_ner(text, model)
 
 
 
 
202
  return JSONResponse(content=result)
203
 
204
 
 
207
  tags=["Documentación"],
208
  summary="Documentación HTML del servicio",
209
  response_class=HTMLResponse,
210
+ include_in_schema=False,
211
  )
212
  def docu():
213
+ """Página HTML autodocumentada. **No requiere autenticación.**"""
 
 
 
 
214
  schema = get_openapi(
215
  title=app.title,
216
  version=app.version,
 
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); }}
 
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
  </div>
320
  </section>
321
 
322
+ <section>
323
+ <h2>Modelos disponibles</h2>
324
+ <div class="model-box">
325
+ <p><code>ruler</code> — <strong>Spacy Ruler (Sentences)</strong><br/>
326
+ Detecta entidades generales con reglas sobre oraciones.</p>
327
+ <br/>
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
 
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>
365
  </section>
366
 
367
  </main>
requirements.txt CHANGED
@@ -1,4 +1,6 @@
1
  fastapi
2
  uvicorn[standard]
3
  python-multipart
4
- spacy>=3.8.0
 
 
 
1
  fastapi
2
  uvicorn[standard]
3
  python-multipart
4
+ spacy>=3.8.0
5
+ pandas
6
+ beautifulsoup4