Spaces:
Sleeping
Sleeping
Commit ·
1c4d3f9
1
Parent(s): ed3db4e
Mise à jour Backend, Exploit NER & OCR HF pour extraire des PDF et enrichire ca_membres
Browse files- app/api/enrichment.py +183 -55
- packages.txt +4 -0
- requirements.txt +6 -0
app/api/enrichment.py
CHANGED
|
@@ -1,10 +1,29 @@
|
|
| 1 |
-
from fastapi import APIRouter, HTTPException,
|
| 2 |
-
from typing import List, Optional
|
| 3 |
from pydantic import BaseModel
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
import uuid
|
|
|
|
|
|
|
|
|
|
| 6 |
import math
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from app.core.supabase_client import get_user_client, get_admin_client
|
| 9 |
from app.services.auth_service import get_current_user, get_current_active_user, AuthenticatedUserInfo
|
| 10 |
|
|
@@ -156,10 +175,14 @@ class WatchCompanyUpdate(BaseModel):
|
|
| 156 |
detected_trovit_charika_id: Optional[str] = None
|
| 157 |
detected_trovit_url: Optional[str] = None
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
# --- Business Logic ---
|
| 160 |
|
| 161 |
def calculate_red_flags(data: EnrichmentData) -> Metrics:
|
| 162 |
-
# Defensive data handling
|
| 163 |
contracts = getattr(data.marches, "contracts", []) or []
|
| 164 |
total_contracts = len(contracts)
|
| 165 |
total_value = sum((c.montant or 0) for c in contracts)
|
|
@@ -280,7 +303,7 @@ def save_manual_enrichment(
|
|
| 280 |
|
| 281 |
@router.get("/profile/{company_id}")
|
| 282 |
def get_enriched_profile(company_id: str):
|
| 283 |
-
client = get_user_client()
|
| 284 |
resp = client.table("enriched_companies").select("*").eq("company_id", company_id).execute()
|
| 285 |
if not resp.data:
|
| 286 |
raise HTTPException(status_code=404, detail="Profile not enriched yet")
|
|
@@ -289,7 +312,7 @@ def get_enriched_profile(company_id: str):
|
|
| 289 |
|
| 290 |
@router.get("/status/{company_id}")
|
| 291 |
def check_enrichment_status(company_id: str):
|
| 292 |
-
client = get_user_client()
|
| 293 |
resp = client.table("enriched_companies").select("company_id").eq("company_id", company_id).execute()
|
| 294 |
return {
|
| 295 |
"company_id": company_id,
|
|
@@ -299,7 +322,7 @@ def check_enrichment_status(company_id: str):
|
|
| 299 |
|
| 300 |
@router.get("/all")
|
| 301 |
def get_all_enriched():
|
| 302 |
-
client = get_user_client()
|
| 303 |
resp = client.table("enriched_companies").select("*").order("enriched_at", desc=True).execute()
|
| 304 |
return [format_company_dict(c) for c in resp.data]
|
| 305 |
|
|
@@ -312,13 +335,8 @@ def list_enriched_companies(
|
|
| 312 |
wilaya: Optional[str] = None,
|
| 313 |
has_red_flags: Optional[bool] = None
|
| 314 |
):
|
| 315 |
-
client = get_user_client()
|
| 316 |
-
|
| 317 |
-
# Supabase doesn't easily support complex JSON filtering via simple postgrest for the red_flags logic
|
| 318 |
-
# we had in sqlite, so we may need to fetch more or use an RPC.
|
| 319 |
-
# For now, fetching all and filtering in memory (simulating the previous behavior).
|
| 320 |
resp = client.table("enriched_companies").select("*").order("enriched_at", desc=True).execute()
|
| 321 |
-
|
| 322 |
companies_dicts = [format_company_dict(c) for c in resp.data]
|
| 323 |
|
| 324 |
if search:
|
|
@@ -351,17 +369,153 @@ def delete_enriched_company(
|
|
| 351 |
company_id: str,
|
| 352 |
current_user: AuthenticatedUserInfo = Depends(get_current_user)
|
| 353 |
):
|
| 354 |
-
# Relying on RLS: if user is not admin, RLS policy will reject DELETE.
|
| 355 |
client = get_user_client(current_user.jwt)
|
| 356 |
try:
|
| 357 |
resp = client.table("enriched_companies").delete().eq("company_id", company_id).execute()
|
| 358 |
if not resp.data:
|
| 359 |
-
# PostgREST returns empty data if 0 rows deleted (due to RLS or missing)
|
| 360 |
raise HTTPException(status_code=403, detail="Permission denied or company not found (admin only).")
|
| 361 |
return {"status": "success"}
|
| 362 |
except Exception as e:
|
| 363 |
raise HTTPException(status_code=403, detail="Vous n'avez pas les droits pour supprimer cet élément (admin uniquement).")
|
| 364 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
|
| 366 |
# --- Investigation Notes Endpoints ---
|
| 367 |
|
|
@@ -371,12 +525,10 @@ def create_note(
|
|
| 371 |
request: CreateNoteRequest,
|
| 372 |
current_user: AuthenticatedUserInfo = Depends(get_current_user)
|
| 373 |
):
|
| 374 |
-
# Public read check for company
|
| 375 |
client_anon = get_user_client()
|
| 376 |
company_resp = client_anon.table("enriched_companies").select("company_id").eq("company_id", company_id).execute()
|
| 377 |
if not company_resp.data:
|
| 378 |
raise HTTPException(status_code=404, detail="Company not found")
|
| 379 |
-
|
| 380 |
now = datetime.utcnow().isoformat()
|
| 381 |
note_payload = {
|
| 382 |
"id": str(uuid.uuid4()),
|
|
@@ -389,7 +541,6 @@ def create_note(
|
|
| 389 |
"updated_at": now,
|
| 390 |
"auth_user_id": current_user.user_id
|
| 391 |
}
|
| 392 |
-
|
| 393 |
client = get_user_client(current_user.jwt)
|
| 394 |
try:
|
| 395 |
resp = client.table("investigation_notes").insert(note_payload).execute()
|
|
@@ -400,7 +551,7 @@ def create_note(
|
|
| 400 |
"total_notes": total_resp.count if total_resp else 0
|
| 401 |
}
|
| 402 |
except Exception as e:
|
| 403 |
-
raise HTTPException(status_code=403, detail="Permission denied
|
| 404 |
|
| 405 |
|
| 406 |
@router.get("/{company_id}/notes")
|
|
@@ -412,19 +563,11 @@ def get_notes(
|
|
| 412 |
company_resp = client_anon.table("enriched_companies").select("company_name").eq("company_id", company_id).execute()
|
| 413 |
if not company_resp.data:
|
| 414 |
raise HTTPException(status_code=404, detail="Company not found")
|
| 415 |
-
|
| 416 |
-
# ADMIN can see ALL notes, regular users see only their OWN (enforced by code + RLS)
|
| 417 |
if current_user.is_admin:
|
| 418 |
-
# Admin specifically uses admin_client to bypass RLS or uses user_client if RLS policy allows admin to see all
|
| 419 |
-
# Let's use get_user_client for now and assume RLS handles it, or explicit filter if needed.
|
| 420 |
-
client = get_user_client(current_user.jwt)
|
| 421 |
-
# Admins don't filter by auth_user_id
|
| 422 |
query = client.table("investigation_notes").select("*").eq("company_id", company_id)
|
| 423 |
else:
|
| 424 |
-
client = get_user_client(current_user.jwt)
|
| 425 |
-
# Regular users only see their own
|
| 426 |
query = client.table("investigation_notes").select("*").eq("company_id", company_id).eq("auth_user_id", current_user.user_id)
|
| 427 |
-
|
| 428 |
try:
|
| 429 |
notes_resp = query.order("created_at", desc=True).execute()
|
| 430 |
return {
|
|
@@ -434,7 +577,7 @@ def get_notes(
|
|
| 434 |
"total": len(notes_resp.data)
|
| 435 |
}
|
| 436 |
except Exception as e:
|
| 437 |
-
raise HTTPException(status_code=403, detail="Permission denied
|
| 438 |
|
| 439 |
|
| 440 |
@router.put("/{company_id}/notes/{note_id}")
|
|
@@ -449,17 +592,13 @@ def update_note(
|
|
| 449 |
if updates.title is not None: update_payload["title"] = updates.title
|
| 450 |
if updates.content is not None: update_payload["content"] = updates.content
|
| 451 |
if updates.tags is not None: update_payload["tags"] = updates.tags
|
| 452 |
-
|
| 453 |
try:
|
| 454 |
resp = client.table("investigation_notes").update(update_payload).eq("id", note_id).eq("company_id", company_id).execute()
|
| 455 |
if not resp.data:
|
| 456 |
-
raise HTTPException(status_code=403, detail="
|
| 457 |
-
return {
|
| 458 |
-
"status": "success",
|
| 459 |
-
"note": resp.data[0]
|
| 460 |
-
}
|
| 461 |
except Exception as e:
|
| 462 |
-
raise HTTPException(status_code=403, detail="
|
| 463 |
|
| 464 |
|
| 465 |
@router.delete("/{company_id}/notes/{note_id}")
|
|
@@ -472,16 +611,11 @@ def delete_note(
|
|
| 472 |
try:
|
| 473 |
resp = client.table("investigation_notes").delete().eq("id", note_id).eq("company_id", company_id).execute()
|
| 474 |
if not resp.data:
|
| 475 |
-
raise HTTPException(status_code=403, detail="
|
| 476 |
-
|
| 477 |
remaining_resp = client.table("investigation_notes").select("id", count="exact").eq("company_id", company_id).execute()
|
| 478 |
-
return {
|
| 479 |
-
"status": "success",
|
| 480 |
-
"deleted_note_id": note_id,
|
| 481 |
-
"total_notes": remaining_resp.count if remaining_resp else 0
|
| 482 |
-
}
|
| 483 |
except Exception as e:
|
| 484 |
-
raise HTTPException(status_code=403, detail="
|
| 485 |
|
| 486 |
|
| 487 |
# --- Watchlist Endpoints ---
|
|
@@ -492,12 +626,11 @@ def list_watch_companies(
|
|
| 492 |
etat: Optional[str] = None,
|
| 493 |
q: Optional[str] = None
|
| 494 |
):
|
| 495 |
-
client = get_user_client()
|
| 496 |
query = client.table("watch_companies").select("*")
|
| 497 |
if wilaya: query = query.eq("wilaya", wilaya)
|
| 498 |
if etat: query = query.eq("etat_enregistrement", etat)
|
| 499 |
if q: query = query.ilike("name_ar", f"%{q}%")
|
| 500 |
-
|
| 501 |
resp = query.order("created_at", desc=True).execute()
|
| 502 |
return resp.data
|
| 503 |
|
|
@@ -509,27 +642,22 @@ def update_watch_company(
|
|
| 509 |
current_user: AuthenticatedUserInfo = Depends(get_current_user)
|
| 510 |
):
|
| 511 |
client = get_user_client(current_user.jwt)
|
| 512 |
-
|
| 513 |
update_data = {"updated_at": datetime.utcnow().isoformat()}
|
| 514 |
if updates.etat_enregistrement is not None:
|
| 515 |
update_data["etat_enregistrement"] = updates.etat_enregistrement
|
| 516 |
if updates.etat_enregistrement == "detected_trovit":
|
| 517 |
-
# We should theoretically fetch the row to see if detected_trovit_at is null,
|
| 518 |
-
# but to save a query, we can just set it if we're setting it to this state.
|
| 519 |
update_data["detected_trovit_at"] = datetime.utcnow().isoformat()
|
| 520 |
-
|
| 521 |
if updates.detected_trovit_charika_id is not None:
|
| 522 |
update_data["detected_trovit_charika_id"] = updates.detected_trovit_charika_id
|
| 523 |
if updates.detected_trovit_url is not None:
|
| 524 |
update_data["detected_trovit_url"] = updates.detected_trovit_url
|
| 525 |
-
|
| 526 |
try:
|
| 527 |
resp = client.table("watch_companies").update(update_data).eq("id", company_id).execute()
|
| 528 |
if not resp.data:
|
| 529 |
-
raise HTTPException(status_code=403, detail="
|
| 530 |
return resp.data[0]
|
| 531 |
except Exception as e:
|
| 532 |
-
raise HTTPException(status_code=403, detail="
|
| 533 |
|
| 534 |
@router.delete("/watch-companies/{company_id}")
|
| 535 |
def delete_watch_company(
|
|
@@ -540,7 +668,7 @@ def delete_watch_company(
|
|
| 540 |
try:
|
| 541 |
resp = client.table("watch_companies").delete().eq("id", company_id).execute()
|
| 542 |
if not resp.data:
|
| 543 |
-
raise HTTPException(status_code=403, detail="
|
| 544 |
return {"status": "success"}
|
| 545 |
except Exception as e:
|
| 546 |
-
raise HTTPException(status_code=403, detail="
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
|
| 2 |
+
from typing import List, Optional, Dict
|
| 3 |
from pydantic import BaseModel
|
| 4 |
+
import os
|
| 5 |
+
import io
|
| 6 |
+
import re
|
| 7 |
import uuid
|
| 8 |
+
import json
|
| 9 |
+
import requests
|
| 10 |
+
from datetime import datetime
|
| 11 |
import math
|
| 12 |
|
| 13 |
+
import pdfplumber
|
| 14 |
+
import pytesseract
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
# For ZeroGPU support on HF
|
| 18 |
+
try:
|
| 19 |
+
import spaces
|
| 20 |
+
except ImportError:
|
| 21 |
+
# Fallback for local testing
|
| 22 |
+
class spaces:
|
| 23 |
+
@staticmethod
|
| 24 |
+
def GPU(func):
|
| 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 |
|
|
|
|
| 175 |
detected_trovit_charika_id: Optional[str] = None
|
| 176 |
detected_trovit_url: Optional[str] = None
|
| 177 |
|
| 178 |
+
class MemberCreateRequest(BaseModel):
|
| 179 |
+
full_name: str
|
| 180 |
+
role: str
|
| 181 |
+
source_document_url: Optional[str] = None
|
| 182 |
+
|
| 183 |
# --- Business Logic ---
|
| 184 |
|
| 185 |
def calculate_red_flags(data: EnrichmentData) -> Metrics:
|
|
|
|
| 186 |
contracts = getattr(data.marches, "contracts", []) or []
|
| 187 |
total_contracts = len(contracts)
|
| 188 |
total_value = sum((c.montant or 0) for c in contracts)
|
|
|
|
| 303 |
|
| 304 |
@router.get("/profile/{company_id}")
|
| 305 |
def get_enriched_profile(company_id: str):
|
| 306 |
+
client = get_user_client()
|
| 307 |
resp = client.table("enriched_companies").select("*").eq("company_id", company_id).execute()
|
| 308 |
if not resp.data:
|
| 309 |
raise HTTPException(status_code=404, detail="Profile not enriched yet")
|
|
|
|
| 312 |
|
| 313 |
@router.get("/status/{company_id}")
|
| 314 |
def check_enrichment_status(company_id: str):
|
| 315 |
+
client = get_user_client()
|
| 316 |
resp = client.table("enriched_companies").select("company_id").eq("company_id", company_id).execute()
|
| 317 |
return {
|
| 318 |
"company_id": company_id,
|
|
|
|
| 322 |
|
| 323 |
@router.get("/all")
|
| 324 |
def get_all_enriched():
|
| 325 |
+
client = get_user_client()
|
| 326 |
resp = client.table("enriched_companies").select("*").order("enriched_at", desc=True).execute()
|
| 327 |
return [format_company_dict(c) for c in resp.data]
|
| 328 |
|
|
|
|
| 335 |
wilaya: Optional[str] = None,
|
| 336 |
has_red_flags: Optional[bool] = None
|
| 337 |
):
|
| 338 |
+
client = get_user_client()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
resp = client.table("enriched_companies").select("*").order("enriched_at", desc=True).execute()
|
|
|
|
| 340 |
companies_dicts = [format_company_dict(c) for c in resp.data]
|
| 341 |
|
| 342 |
if search:
|
|
|
|
| 369 |
company_id: str,
|
| 370 |
current_user: AuthenticatedUserInfo = Depends(get_current_user)
|
| 371 |
):
|
|
|
|
| 372 |
client = get_user_client(current_user.jwt)
|
| 373 |
try:
|
| 374 |
resp = client.table("enriched_companies").delete().eq("company_id", company_id).execute()
|
| 375 |
if not resp.data:
|
|
|
|
| 376 |
raise HTTPException(status_code=403, detail="Permission denied or company not found (admin only).")
|
| 377 |
return {"status": "success"}
|
| 378 |
except Exception as e:
|
| 379 |
raise HTTPException(status_code=403, detail="Vous n'avez pas les droits pour supprimer cet élément (admin uniquement).")
|
| 380 |
|
| 381 |
+
# --- HF NER & Root Cleaning Logic ---
|
| 382 |
+
|
| 383 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 384 |
+
NER_MODEL = "hatem-h/bert-base-arabic-ner"
|
| 385 |
+
|
| 386 |
+
def clean_surname_root(name: str) -> str:
|
| 387 |
+
if not name: return ""
|
| 388 |
+
prefixes = ["بن", "ال", "ابن", "بو", "ولد"]
|
| 389 |
+
name = re.sub(r'[^\u0621-\u064A\s]', '', name).strip()
|
| 390 |
+
words = name.split()
|
| 391 |
+
if not words: return ""
|
| 392 |
+
last_word = words[-1]
|
| 393 |
+
if last_word.startswith("ال") and len(last_word) > 4:
|
| 394 |
+
last_word = last_word[2:]
|
| 395 |
+
return last_word
|
| 396 |
+
|
| 397 |
+
def query_hf_ner(text: str) -> List[Dict]:
|
| 398 |
+
if not HF_TOKEN or not text: return []
|
| 399 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 400 |
+
api_url = f"https://api-inference.huggingface.co/models/{NER_MODEL}"
|
| 401 |
+
try:
|
| 402 |
+
payload = {"inputs": text[:1500]}
|
| 403 |
+
response = requests.post(api_url, headers=headers, json=payload, timeout=10)
|
| 404 |
+
return response.json()
|
| 405 |
+
except Exception as e:
|
| 406 |
+
print(f"HF API Error: {e}")
|
| 407 |
+
return []
|
| 408 |
+
|
| 409 |
+
def extract_names_from_text(text: str) -> List[dict]:
|
| 410 |
+
if not text: return []
|
| 411 |
+
ner_results = query_hf_ner(text)
|
| 412 |
+
names = []
|
| 413 |
+
current_name = []
|
| 414 |
+
for entity in ner_results:
|
| 415 |
+
if isinstance(entity, dict) and 'entity_group' in entity:
|
| 416 |
+
if entity['entity_group'] == 'PERS':
|
| 417 |
+
word = entity['word'].replace('##', '')
|
| 418 |
+
if entity['entity'].startswith('B-'):
|
| 419 |
+
if current_name: names.append(" ".join(current_name))
|
| 420 |
+
current_name = [word]
|
| 421 |
+
else:
|
| 422 |
+
current_name.append(word)
|
| 423 |
+
if current_name: names.append(" ".join(current_name))
|
| 424 |
+
clean_names = list(set([n.replace(' ', '') if '##' in n else n for n in names]))
|
| 425 |
+
|
| 426 |
+
roles_map = {
|
| 427 |
+
"رئيس مجلس الإدارة": ["رئيس", "الرئيس"],
|
| 428 |
+
"نائب رئيس": ["نائب", "النائب"],
|
| 429 |
+
"عضو": ["عضو", "العضو"]
|
| 430 |
+
}
|
| 431 |
+
results = []
|
| 432 |
+
text_normalized = " ".join(text.split())
|
| 433 |
+
for name in clean_names:
|
| 434 |
+
if len(name) < 5: continue
|
| 435 |
+
best_role = "عضو"
|
| 436 |
+
min_dist = 100
|
| 437 |
+
for canonical_role, keywords in roles_map.items():
|
| 438 |
+
for kw in keywords:
|
| 439 |
+
for m in re.finditer(kw, text_normalized):
|
| 440 |
+
dist = abs(m.start() - text_normalized.find(name))
|
| 441 |
+
if dist < min_dist and dist < 100:
|
| 442 |
+
min_dist = dist
|
| 443 |
+
best_role = canonical_role
|
| 444 |
+
results.append({"full_name": name, "role": best_role})
|
| 445 |
+
return results
|
| 446 |
+
|
| 447 |
+
@spaces.GPU
|
| 448 |
+
def run_ocr(content: bytes, is_image: bool = False) -> str:
|
| 449 |
+
try:
|
| 450 |
+
if is_image:
|
| 451 |
+
img = Image.open(io.BytesIO(content))
|
| 452 |
+
return pytesseract.image_to_string(img, lang='ara')
|
| 453 |
+
else:
|
| 454 |
+
import pdf2image
|
| 455 |
+
images = pdf2image.convert_from_bytes(content, first_page=1, last_page=3)
|
| 456 |
+
full_text = ""
|
| 457 |
+
for img in images:
|
| 458 |
+
full_text += pytesseract.image_to_string(img, lang='ara') + "\n"
|
| 459 |
+
return full_text
|
| 460 |
+
except Exception as e:
|
| 461 |
+
print(f"OCR local error: {e}")
|
| 462 |
+
return ""
|
| 463 |
+
|
| 464 |
+
@router.post("/extract-pv")
|
| 465 |
+
async def extract_pv_data(
|
| 466 |
+
file: UploadFile,
|
| 467 |
+
current_user: AuthenticatedUserInfo = Depends(get_current_active_user)
|
| 468 |
+
):
|
| 469 |
+
if not current_user.is_admin:
|
| 470 |
+
raise HTTPException(status_code=403, detail="Admin access required")
|
| 471 |
+
content = await file.read()
|
| 472 |
+
text = ""
|
| 473 |
+
try:
|
| 474 |
+
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
| 475 |
+
for page in pdf.pages:
|
| 476 |
+
page_text = page.extract_text()
|
| 477 |
+
if page_text: text += page_text + "\n"
|
| 478 |
+
except Exception as e:
|
| 479 |
+
print(f"pdfplumber error: {e}")
|
| 480 |
+
if len(text.strip()) < 50:
|
| 481 |
+
is_img = file.content_type.startswith("image/")
|
| 482 |
+
text = run_ocr(content, is_image=is_img)
|
| 483 |
+
members = extract_names_from_text(text)
|
| 484 |
+
return {
|
| 485 |
+
"filename": file.filename,
|
| 486 |
+
"suggested_members": members,
|
| 487 |
+
"method": "OCR" if len(text.strip()) >= 50 else "Native/NER"
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
@router.post("/{company_id}/members")
|
| 491 |
+
def save_company_members(
|
| 492 |
+
company_id: str,
|
| 493 |
+
members: List[MemberCreateRequest],
|
| 494 |
+
current_user: AuthenticatedUserInfo = Depends(get_current_active_user)
|
| 495 |
+
):
|
| 496 |
+
if not current_user.is_admin:
|
| 497 |
+
raise HTTPException(status_code=403, detail="Admin required")
|
| 498 |
+
client = get_user_client(current_user.jwt)
|
| 499 |
+
db_payloads = []
|
| 500 |
+
for m in members:
|
| 501 |
+
db_payloads.append({
|
| 502 |
+
"id": str(uuid.uuid4()),
|
| 503 |
+
"company_id": company_id,
|
| 504 |
+
"full_name": m.full_name,
|
| 505 |
+
"role": m.role,
|
| 506 |
+
"added_by": current_user.email,
|
| 507 |
+
"source_document_url": m.source_document_url,
|
| 508 |
+
"created_at": datetime.utcnow().isoformat()
|
| 509 |
+
})
|
| 510 |
+
client.table("sc_members").delete().eq("company_id", company_id).execute()
|
| 511 |
+
resp = client.table("sc_members").insert(db_payloads).execute()
|
| 512 |
+
return {"status": "success", "count": len(resp.data)}
|
| 513 |
+
|
| 514 |
+
@router.get("/{company_id}/members")
|
| 515 |
+
def get_company_members(company_id: str):
|
| 516 |
+
client = get_user_client()
|
| 517 |
+
resp = client.table("sc_members").select("*").eq("company_id", company_id).execute()
|
| 518 |
+
return resp.data
|
| 519 |
|
| 520 |
# --- Investigation Notes Endpoints ---
|
| 521 |
|
|
|
|
| 525 |
request: CreateNoteRequest,
|
| 526 |
current_user: AuthenticatedUserInfo = Depends(get_current_user)
|
| 527 |
):
|
|
|
|
| 528 |
client_anon = get_user_client()
|
| 529 |
company_resp = client_anon.table("enriched_companies").select("company_id").eq("company_id", company_id).execute()
|
| 530 |
if not company_resp.data:
|
| 531 |
raise HTTPException(status_code=404, detail="Company not found")
|
|
|
|
| 532 |
now = datetime.utcnow().isoformat()
|
| 533 |
note_payload = {
|
| 534 |
"id": str(uuid.uuid4()),
|
|
|
|
| 541 |
"updated_at": now,
|
| 542 |
"auth_user_id": current_user.user_id
|
| 543 |
}
|
|
|
|
| 544 |
client = get_user_client(current_user.jwt)
|
| 545 |
try:
|
| 546 |
resp = client.table("investigation_notes").insert(note_payload).execute()
|
|
|
|
| 551 |
"total_notes": total_resp.count if total_resp else 0
|
| 552 |
}
|
| 553 |
except Exception as e:
|
| 554 |
+
raise HTTPException(status_code=403, detail="Permission denied")
|
| 555 |
|
| 556 |
|
| 557 |
@router.get("/{company_id}/notes")
|
|
|
|
| 563 |
company_resp = client_anon.table("enriched_companies").select("company_name").eq("company_id", company_id).execute()
|
| 564 |
if not company_resp.data:
|
| 565 |
raise HTTPException(status_code=404, detail="Company not found")
|
| 566 |
+
client = get_user_client(current_user.jwt)
|
|
|
|
| 567 |
if current_user.is_admin:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
query = client.table("investigation_notes").select("*").eq("company_id", company_id)
|
| 569 |
else:
|
|
|
|
|
|
|
| 570 |
query = client.table("investigation_notes").select("*").eq("company_id", company_id).eq("auth_user_id", current_user.user_id)
|
|
|
|
| 571 |
try:
|
| 572 |
notes_resp = query.order("created_at", desc=True).execute()
|
| 573 |
return {
|
|
|
|
| 577 |
"total": len(notes_resp.data)
|
| 578 |
}
|
| 579 |
except Exception as e:
|
| 580 |
+
raise HTTPException(status_code=403, detail="Permission denied")
|
| 581 |
|
| 582 |
|
| 583 |
@router.put("/{company_id}/notes/{note_id}")
|
|
|
|
| 592 |
if updates.title is not None: update_payload["title"] = updates.title
|
| 593 |
if updates.content is not None: update_payload["content"] = updates.content
|
| 594 |
if updates.tags is not None: update_payload["tags"] = updates.tags
|
|
|
|
| 595 |
try:
|
| 596 |
resp = client.table("investigation_notes").update(update_payload).eq("id", note_id).eq("company_id", company_id).execute()
|
| 597 |
if not resp.data:
|
| 598 |
+
raise HTTPException(status_code=403, detail="Access denied")
|
| 599 |
+
return {"status": "success", "note": resp.data[0]}
|
|
|
|
|
|
|
|
|
|
| 600 |
except Exception as e:
|
| 601 |
+
raise HTTPException(status_code=403, detail="Update failed")
|
| 602 |
|
| 603 |
|
| 604 |
@router.delete("/{company_id}/notes/{note_id}")
|
|
|
|
| 611 |
try:
|
| 612 |
resp = client.table("investigation_notes").delete().eq("id", note_id).eq("company_id", company_id).execute()
|
| 613 |
if not resp.data:
|
| 614 |
+
raise HTTPException(status_code=403, detail="Delete failed")
|
|
|
|
| 615 |
remaining_resp = client.table("investigation_notes").select("id", count="exact").eq("company_id", company_id).execute()
|
| 616 |
+
return {"status": "success", "deleted_note_id": note_id, "total_notes": remaining_resp.count}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 617 |
except Exception as e:
|
| 618 |
+
raise HTTPException(status_code=403, detail="Delete denied")
|
| 619 |
|
| 620 |
|
| 621 |
# --- Watchlist Endpoints ---
|
|
|
|
| 626 |
etat: Optional[str] = None,
|
| 627 |
q: Optional[str] = None
|
| 628 |
):
|
| 629 |
+
client = get_user_client()
|
| 630 |
query = client.table("watch_companies").select("*")
|
| 631 |
if wilaya: query = query.eq("wilaya", wilaya)
|
| 632 |
if etat: query = query.eq("etat_enregistrement", etat)
|
| 633 |
if q: query = query.ilike("name_ar", f"%{q}%")
|
|
|
|
| 634 |
resp = query.order("created_at", desc=True).execute()
|
| 635 |
return resp.data
|
| 636 |
|
|
|
|
| 642 |
current_user: AuthenticatedUserInfo = Depends(get_current_user)
|
| 643 |
):
|
| 644 |
client = get_user_client(current_user.jwt)
|
|
|
|
| 645 |
update_data = {"updated_at": datetime.utcnow().isoformat()}
|
| 646 |
if updates.etat_enregistrement is not None:
|
| 647 |
update_data["etat_enregistrement"] = updates.etat_enregistrement
|
| 648 |
if updates.etat_enregistrement == "detected_trovit":
|
|
|
|
|
|
|
| 649 |
update_data["detected_trovit_at"] = datetime.utcnow().isoformat()
|
|
|
|
| 650 |
if updates.detected_trovit_charika_id is not None:
|
| 651 |
update_data["detected_trovit_charika_id"] = updates.detected_trovit_charika_id
|
| 652 |
if updates.detected_trovit_url is not None:
|
| 653 |
update_data["detected_trovit_url"] = updates.detected_trovit_url
|
|
|
|
| 654 |
try:
|
| 655 |
resp = client.table("watch_companies").update(update_data).eq("id", company_id).execute()
|
| 656 |
if not resp.data:
|
| 657 |
+
raise HTTPException(status_code=403, detail="Access denied")
|
| 658 |
return resp.data[0]
|
| 659 |
except Exception as e:
|
| 660 |
+
raise HTTPException(status_code=403, detail="Update denied")
|
| 661 |
|
| 662 |
@router.delete("/watch-companies/{company_id}")
|
| 663 |
def delete_watch_company(
|
|
|
|
| 668 |
try:
|
| 669 |
resp = client.table("watch_companies").delete().eq("id", company_id).execute()
|
| 670 |
if not resp.data:
|
| 671 |
+
raise HTTPException(status_code=403, detail="Delete denied")
|
| 672 |
return {"status": "success"}
|
| 673 |
except Exception as e:
|
| 674 |
+
raise HTTPException(status_code=403, detail="Delete failed")
|
packages.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tesseract-ocr
|
| 2 |
+
tesseract-ocr-ara
|
| 3 |
+
libgl1-mesa-glx
|
| 4 |
+
poppler-utils
|
requirements.txt
CHANGED
|
@@ -64,3 +64,9 @@ thefuzz==0.22.1
|
|
| 64 |
python-Levenshtein==0.27.3
|
| 65 |
|
| 66 |
supabase==2.27.3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
python-Levenshtein==0.27.3
|
| 65 |
|
| 66 |
supabase==2.27.3
|
| 67 |
+
|
| 68 |
+
pdfplumber==0.11.0
|
| 69 |
+
pdf2image==1.17.0
|
| 70 |
+
pytesseract==0.3.13
|
| 71 |
+
Pillow==11.1.0
|
| 72 |
+
requests==2.32.3
|