Ba7ath-Project commited on
Commit
763f5fe
·
1 Parent(s): 517cf4b

Crud Card MAJ backend

Browse files
Files changed (2) hide show
  1. app/api/enrichment.py +3 -13
  2. app/services/ner_service.py +14 -35
app/api/enrichment.py CHANGED
@@ -25,9 +25,9 @@ except ImportError:
25
  return func
26
 
27
  from app.core.supabase_client import get_user_client, get_admin_client
28
- from app.services.auth_service import get_current_user, get_current_active_user, AuthenticatedUserInfo
29
 
30
- router = APIRouter() # Enrichment Router
31
 
32
  # --- UTILITY FUNCTIONS ---
33
 
@@ -115,18 +115,10 @@ class Contract(BaseModel):
115
  class MarchesData(BaseModel):
116
  contracts: List[Contract] = []
117
 
118
- class AhlyaData(BaseModel):
119
- activity: Optional[str] = None
120
- address: Optional[str] = None
121
- delegation: Optional[str] = None
122
- area: Optional[str] = None
123
- type: Optional[str] = None
124
-
125
  class EnrichmentData(BaseModel):
126
  rne: RneData
127
  jort: JortData
128
  marches: MarchesData
129
- ahlya: Optional[AhlyaData] = None
130
  notes: Optional[str] = None
131
 
132
  class RedFlag(BaseModel):
@@ -237,7 +229,6 @@ def format_company_dict(company: dict) -> dict:
237
  rne = safe_data.get("rne") if isinstance(safe_data.get("rne"), dict) else {}
238
  jort = safe_data.get("jort") if isinstance(safe_data.get("jort"), dict) else {}
239
  marches = safe_data.get("marches") if isinstance(safe_data.get("marches"), dict) else {}
240
- ahlya = safe_data.get("ahlya") if isinstance(safe_data.get("ahlya"), dict) else {}
241
  raw = safe_data.get("raw") if isinstance(safe_data.get("raw"), dict) else {}
242
 
243
  safe_rne = {
@@ -266,7 +257,6 @@ def format_company_dict(company: dict) -> dict:
266
  "rne": safe_rne,
267
  "jort": safe_jort,
268
  "marches": safe_marches,
269
- "ahlya": ahlya,
270
  "raw": raw
271
  },
272
  "metrics": safe_metrics_dict,
@@ -377,7 +367,7 @@ def list_enriched_companies(
377
  @router.delete("/profile/{company_id}")
378
  def delete_enriched_company(
379
  company_id: str,
380
- current_user: AuthenticatedUserInfo = Depends(get_current_user)
381
  ):
382
  client = get_user_client(current_user.jwt)
383
  try:
 
25
  return func
26
 
27
  from app.core.supabase_client import get_user_client, get_admin_client
28
+ from app.services.auth_service import get_current_user, get_current_active_user, get_current_admin_user, AuthenticatedUserInfo
29
 
30
+ router = APIRouter()
31
 
32
  # --- UTILITY FUNCTIONS ---
33
 
 
115
  class MarchesData(BaseModel):
116
  contracts: List[Contract] = []
117
 
 
 
 
 
 
 
 
118
  class EnrichmentData(BaseModel):
119
  rne: RneData
120
  jort: JortData
121
  marches: MarchesData
 
122
  notes: Optional[str] = None
123
 
124
  class RedFlag(BaseModel):
 
229
  rne = safe_data.get("rne") if isinstance(safe_data.get("rne"), dict) else {}
230
  jort = safe_data.get("jort") if isinstance(safe_data.get("jort"), dict) else {}
231
  marches = safe_data.get("marches") if isinstance(safe_data.get("marches"), dict) else {}
 
232
  raw = safe_data.get("raw") if isinstance(safe_data.get("raw"), dict) else {}
233
 
234
  safe_rne = {
 
257
  "rne": safe_rne,
258
  "jort": safe_jort,
259
  "marches": safe_marches,
 
260
  "raw": raw
261
  },
262
  "metrics": safe_metrics_dict,
 
367
  @router.delete("/profile/{company_id}")
368
  def delete_enriched_company(
369
  company_id: str,
370
+ current_user: AuthenticatedUserInfo = Depends(get_current_admin_user)
371
  ):
372
  client = get_user_client(current_user.jwt)
373
  try:
app/services/ner_service.py CHANGED
@@ -9,40 +9,23 @@ except ImportError:
9
  def GPU(f):
10
  return f
11
 
12
- try:
13
- from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline
14
- TRANSFORMERS_AVAILABLE = True
15
- except ImportError:
16
- TRANSFORMERS_AVAILABLE = False
17
- print("[NER SERVICE] Warning: Transformers/Torch NOT available. NER will be disabled.")
18
 
19
  # Using the requested robust models
20
  MODEL_NAME = "Davlan/xlm-roberta-base-ner-hrl"
21
 
22
- # Global cache for the pipeline
23
- _ner_pipeline = None
24
 
25
- def get_ner_pipeline():
26
- """Lazy initialization of the NER pipeline to avoid hangs on startup."""
27
- global _ner_pipeline
28
- if not TRANSFORMERS_AVAILABLE:
29
- return None
30
-
31
- if _ner_pipeline is None:
32
- print(f"[NER SERVICE] Initializing local pipeline with {MODEL_NAME}...")
33
- try:
34
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
35
- model = AutoModelForTokenClassification.from_pretrained(MODEL_NAME)
36
- _ner_pipeline = pipeline(
37
- "ner",
38
- model=model,
39
- tokenizer=tokenizer,
40
- aggregation_strategy="simple"
41
- )
42
- except Exception as e:
43
- print(f"[NER SERVICE ERROR]: Failed to load pipeline: {e}")
44
- return None
45
- return _ner_pipeline
46
 
47
  @spaces.GPU
48
  def extract_person_entities(text: str) -> List[Dict]:
@@ -50,15 +33,11 @@ def extract_person_entities(text: str) -> List[Dict]:
50
  Extracts PERSON entities using the local transformers pipeline.
51
  Returns: List of { 'text': str, 'label': 'PER', 'start': int, 'end': int }
52
  """
53
- if not TRANSFORMERS_AVAILABLE or not text.strip():
54
  return []
55
 
56
  try:
57
- pipeline_obj = get_ner_pipeline()
58
- if not pipeline_obj:
59
- return []
60
-
61
- raw = pipeline_obj(text)
62
  persons = []
63
  for ent in raw:
64
  # Roberta HRL uses PER or B-PER / I-PER
 
9
  def GPU(f):
10
  return f
11
 
12
+ from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline
 
 
 
 
 
13
 
14
  # Using the requested robust models
15
  MODEL_NAME = "Davlan/xlm-roberta-base-ner-hrl"
16
 
17
+ print(f"[NER SERVICE] Initializing local pipeline with {MODEL_NAME}...")
 
18
 
19
+ # Optional: Lazy loading or ZeroGPU optimization
20
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
21
+ model = AutoModelForTokenClassification.from_pretrained(MODEL_NAME)
22
+
23
+ ner_pipeline = pipeline(
24
+ "ner",
25
+ model=model,
26
+ tokenizer=tokenizer,
27
+ aggregation_strategy="simple"
28
+ )
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  @spaces.GPU
31
  def extract_person_entities(text: str) -> List[Dict]:
 
33
  Extracts PERSON entities using the local transformers pipeline.
34
  Returns: List of { 'text': str, 'label': 'PER', 'start': int, 'end': int }
35
  """
36
+ if not text.strip():
37
  return []
38
 
39
  try:
40
+ raw = ner_pipeline(text)
 
 
 
 
41
  persons = []
42
  for ent in raw:
43
  # Roberta HRL uses PER or B-PER / I-PER