Spaces:
Sleeping
Sleeping
Download backend/main.py from t4transaction/agent: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/t4transaction/agent/resolve/main/backend/main.py
- Command line
-
hf download hf://spaces/t4transaction/agent/backend/main.py
-
curl -L -o main.py https://huggingface.co/spaces/t4transaction/agent/resolve/main/backend/main.py
15 kB
| from __future__ import annotations | |
| import random | |
| import traceback | |
| from pathlib import Path | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import FileResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel, Field | |
| from backend.config import ( | |
| CA_EBITDA_RULE_MESSAGE, | |
| EXCLUDED_URL_MESSAGE, | |
| LIMIT_REQ_PER_DAY, | |
| LIMIT_REQ_PER_MINUTE, | |
| SECURITY_DAY_MESSAGE, | |
| SECURITY_FALLBACK_MESSAGE, | |
| SECURITY_MINUTE_MESSAGE, | |
| VALUATION_KEY_POINTS, | |
| ) | |
| from backend.database import ( | |
| check_usage_policy, | |
| compute_ebitda_valuation, | |
| find_comparable_transactions, | |
| get_usage_policy_state, | |
| register_usage_request, | |
| update_usage_tokens, | |
| ) | |
| from backend.scraper import run_scraper | |
| # API entrypoint unique: orchestre scraping, matching et rendu SPA. | |
| app = FastAPI(title="M&A Headless API", version="0.2.0") | |
| # Contrat d'entree de l'etape 1 (analyse cible). | |
| class AnalyzeRequest(BaseModel): | |
| # URL de la cible a analyser (site vitrine ou corporate). | |
| url: str | |
| # CA saisi en milliers d'euros (kEUR), ex: 1500 = 1,5 MEUR. | |
| ca_keur: float = Field(ge=0) | |
| # EBITDA saisi en kEUR (peut etre negatif selon le business). | |
| ebitda_keur: float | |
| # Scope geographique du matching des transactions comparables. | |
| geo: str = "France" | |
| # Langue UI pour la journalisation/analytics (FR/EN). | |
| lang: str = "fr" | |
| class MatchRequest(BaseModel): | |
| # Mots-cles activites de la cible (issus du scraping/LLM). | |
| keywords: str | |
| # CA cible en EUR (unite backend de calcul). | |
| ca_eur: float = Field(ge=0) | |
| # NAF detaille (optionnel). | |
| naf_code: str | None = None | |
| # NAF sur 2 digits (optionnel). | |
| naf_2: str | None = None | |
| # Geographie cible (France/Europe/International). | |
| geo: str | None = None | |
| # EBITDA cible en kEUR (optionnel) pour calcul valorisation sur /api/comparables. | |
| ebitda_keur: float | None = None | |
| # Nom de la cible (optionnel) pour nommage des audits CSV. | |
| target_name: str | None = None | |
| class ValuationRequest(BaseModel): | |
| # EBITDA en kEUR, converti ensuite en EUR. | |
| ebitda_keur: float | |
| # Multiples pre-calcules a l'etape comparables. | |
| multiples: dict | |
| def _ensure_multiples_contract(multiples: dict) -> dict: | |
| # Garantit un contrat stable "zero null" pour les montants de valorisation. | |
| safe = dict(multiples or {}) | |
| safe.setdefault("valuation_ca_median", 0) | |
| safe.setdefault("valuation_ca_mean", 0) | |
| safe.setdefault("valuation_ebitda_median", 0) | |
| safe.setdefault("valuation_ebitda_mean", 0) | |
| safe.setdefault( | |
| "valuation_ca", | |
| { | |
| "value": 0, | |
| "is_calculable": False, | |
| "reason": "Données insuffisantes même après élargissement", | |
| }, | |
| ) | |
| safe.setdefault( | |
| "valuation_ebitda", | |
| { | |
| "value": 0, | |
| "is_calculable": False, | |
| "reason": "Données insuffisantes même après élargissement", | |
| }, | |
| ) | |
| return safe | |
| def _as_positive_float(value: object) -> float: | |
| """Convertit en float positif; tolere les virgules FR (ex: '6,3').""" | |
| if value is None: | |
| return 0.0 | |
| if isinstance(value, str): | |
| value = value.strip().replace(",", ".") | |
| try: | |
| number = float(value) | |
| except (TypeError, ValueError): | |
| return 0.0 | |
| return number if number > 0 else 0.0 | |
| def _log_api_error(endpoint: str, exc: Exception) -> None: | |
| # Journalise le detail complet dans le terminal backend (diagnostic ops). | |
| print(f"[API_ERROR] endpoint={endpoint} | type={type(exc).__name__} | message={exc}") | |
| print(traceback.format_exc()) | |
| def _public_error_message(status_code: int) -> str: | |
| # Message de repli unique pour statuts securite/erreurs non qualifies. | |
| _ = status_code | |
| return SECURITY_FALLBACK_MESSAGE | |
| def _apply_ebitda_valuations(multiples: dict, ebitda_keur: float | None) -> dict: | |
| """Applique les formules EBITDA median/mean * EBITDA cible avec fallback N/A.""" | |
| safe = _ensure_multiples_contract(multiples) | |
| target_ebitda_eur = (ebitda_keur or 0) * 1000 | |
| target_ebitda_positive = target_ebitda_eur > 0 | |
| ebitda_median_multiple = _as_positive_float(safe.get("ebitda_median")) | |
| ebitda_mean_multiple = _as_positive_float(safe.get("ebitda_mean")) | |
| safe["valuation_ebitda_median"] = ( | |
| int(round(target_ebitda_eur * ebitda_median_multiple)) | |
| if target_ebitda_positive and ebitda_median_multiple > 0 | |
| else "N/A" | |
| ) | |
| safe["valuation_ebitda_mean"] = ( | |
| int(round(target_ebitda_eur * ebitda_mean_multiple)) | |
| if target_ebitda_positive and ebitda_mean_multiple > 0 | |
| else "N/A" | |
| ) | |
| if isinstance(safe["valuation_ebitda_median"], int): | |
| safe["valuation_ebitda"] = { | |
| "value": safe["valuation_ebitda_median"], | |
| "is_calculable": True, | |
| "reason": None, | |
| } | |
| else: | |
| safe["valuation_ebitda"] = { | |
| "value": 0, | |
| "is_calculable": False, | |
| "reason": "N/A - multiple EBITDA absent ou non positif.", | |
| } | |
| return safe | |
| def health() -> dict[str, str]: | |
| # Endpoint de liveness pour verifs locales et plateformes (HF, Docker). | |
| return {"status": "ok"} | |
| def api_analyze(payload: AnalyzeRequest): | |
| # Garde-fou metier: EBITDA positif ne doit pas depasser le CA positif. | |
| if payload.ebitda_keur > 0 and payload.ca_keur > 0 and payload.ebitda_keur > payload.ca_keur: | |
| raise HTTPException(status_code=400, detail={"code": "ebitda_rule", "message": CA_EBITDA_RULE_MESSAGE}) | |
| # Quota global anti-abus (minute/jour) avant toute conso IA. | |
| allowed = check_usage_policy(LIMIT_REQ_PER_MINUTE, LIMIT_REQ_PER_DAY) | |
| if not allowed: | |
| state = get_usage_policy_state() | |
| blocked_reason = str(state.get("blocked_reason") or "").lower() | |
| if blocked_reason == "minute": | |
| raise HTTPException(status_code=429, detail={"code": "security_minute", "message": SECURITY_MINUTE_MESSAGE, "policy": state}) | |
| if blocked_reason == "day": | |
| raise HTTPException(status_code=429, detail={"code": "security_day", "message": SECURITY_DAY_MESSAGE, "policy": state}) | |
| raise HTTPException(status_code=429, detail={"code": "security_fallback", "message": SECURITY_FALLBACK_MESSAGE, "policy": state}) | |
| # Normalisation URL pour fiabiliser scraping + tracking. | |
| clean_url = payload.url.strip() | |
| if not clean_url.startswith(("http://", "https://")): | |
| clean_url = f"https://{clean_url}" | |
| # Trace de requete creee en debut de pipeline pour audit/monitoring. | |
| log_id = register_usage_request( | |
| limit_per_day=LIMIT_REQ_PER_DAY, | |
| user_lang=payload.lang, | |
| target_url=clean_url, | |
| ca_saisi=payload.ca_keur, | |
| ebitda_saisi=payload.ebitda_keur, | |
| ) | |
| tokens_llm = 0 | |
| tokens_embed = 0 | |
| siren = None | |
| keywords = None | |
| try: | |
| # Etape A: scraping intelligent + extraction infos societe. | |
| target_data = run_scraper(clean_url) | |
| tokens_llm = int(target_data.get("tokens_llm", 0) or 0) | |
| siren = target_data.get("siren") | |
| keywords = target_data.get("keywords") | |
| if target_data.get("must_stop"): | |
| # Stop explicite si URL/secteur hors perimetre. | |
| # On renvoie un 200 avec success=False pour que le frontend affiche | |
| # un message metier propre (au lieu d'un echec technique generique). | |
| return { | |
| "success": False, | |
| "must_stop": True, | |
| "stop_reason": target_data.get("stop_reason") or EXCLUDED_URL_MESSAGE, | |
| "target_data": target_data, | |
| } | |
| # Si utilisateur n'a pas de CA, fallback eventuel sur CA officiel. | |
| ca_keur = payload.ca_keur | |
| ca_gov = target_data.get("ca_gov") | |
| if ca_keur == 0 and ca_gov and ca_gov > 0: | |
| # Conversion EUR -> kEUR pour rester coherent avec le contrat frontend. | |
| ca_keur = int(ca_gov / 1000) | |
| # Etape B: matching comparables + calcul de valorisation. | |
| ca_eur = ca_keur * 1000 | |
| results = find_comparable_transactions( | |
| target_keywords=target_data.get("keywords", ""), | |
| target_ca_eur=ca_eur, | |
| target_naf_code=target_data.get("naf_code"), | |
| target_naf_2=target_data.get("naf_2"), | |
| target_geo=payload.geo, | |
| target_name=clean_url, | |
| ) | |
| print(f"[MATCHING] mode={results.get('matching_mode', 'unknown')} | strict_count={results.get('retained_strict_count', 0)} | filtered_count={results.get('filtered_count', 0)}") | |
| tokens_embed = int(results.get("tokens_embed", 0) or 0) | |
| # Contrat unifie: toutes les valorisations doivent vivre sous results.multiples. | |
| multiples = _apply_ebitda_valuations( | |
| results.get("multiples") if isinstance(results.get("multiples"), dict) else {}, | |
| payload.ebitda_keur, | |
| ) | |
| results["multiples"] = multiples | |
| return { | |
| "success": True, | |
| "must_stop": False, | |
| "input": {"url": clean_url, "ca_keur": ca_keur, "ebitda_keur": payload.ebitda_keur, "geo": payload.geo}, | |
| "target_data": target_data, | |
| "results": results, | |
| } | |
| except Exception as exc: | |
| if isinstance(exc, HTTPException): | |
| _log_api_error("/api/analyze", exc) | |
| raise | |
| _log_api_error("/api/analyze", exc) | |
| message = str(exc).lower() | |
| if "rate limit" in message or "status 429" in message: | |
| raise HTTPException(status_code=429, detail={"code": "security_fallback", "message": _public_error_message(429)}) from exc | |
| raise HTTPException(status_code=500, detail={"code": "security_fallback", "message": _public_error_message(500)}) from exc | |
| finally: | |
| # Meme en cas d'erreur, on met a jour la ligne de log usage. | |
| update_usage_tokens( | |
| log_id, | |
| tokens_llm=tokens_llm, | |
| tokens_embed=tokens_embed, | |
| siren=siren, | |
| mots_cles_activites=keywords, | |
| ) | |
| def api_match(payload: MatchRequest): | |
| # Endpoint direct etape comparables (utile pour retests frontend). | |
| try: | |
| results = find_comparable_transactions( | |
| target_keywords=payload.keywords, | |
| target_ca_eur=payload.ca_eur, | |
| target_naf_code=payload.naf_code, | |
| target_naf_2=payload.naf_2, | |
| target_geo=payload.geo, | |
| target_name=payload.target_name, | |
| ) | |
| results["multiples"] = _apply_ebitda_valuations( | |
| results.get("multiples") if isinstance(results.get("multiples"), dict) else {}, | |
| payload.ebitda_keur, | |
| ) | |
| print( | |
| f"[MATCHING] mode={results.get('matching_mode', 'unknown')} | " | |
| f"strict_count={results.get('retained_strict_count', 0)} | filtered_count={results.get('filtered_count', 0)}" | |
| ) | |
| return {"success": True, "results": results} | |
| except Exception as exc: | |
| if isinstance(exc, HTTPException): | |
| _log_api_error("/api/match", exc) | |
| raise | |
| _log_api_error("/api/match", exc) | |
| message = str(exc).lower() | |
| if "rate limit" in message or "status 429" in message: | |
| raise HTTPException(status_code=429, detail={"code": "security_fallback", "message": _public_error_message(429)}) from exc | |
| raise HTTPException(status_code=500, detail={"code": "security_fallback", "message": _public_error_message(500)}) from exc | |
| def api_comparables(payload: MatchRequest): | |
| # Alias lisible cote frontend. | |
| return api_match(payload) | |
| def api_valuation(payload: ValuationRequest): | |
| # Endpoint legacy: renvoie un objet standardise "valuation_ebitda". | |
| try: | |
| valuation = compute_ebitda_valuation(payload.ebitda_keur * 1000, payload.multiples) | |
| return {"success": True, "valuation_ebitda": valuation} | |
| except Exception as exc: | |
| if isinstance(exc, HTTPException): | |
| _log_api_error("/api/valuation", exc) | |
| raise | |
| _log_api_error("/api/valuation", exc) | |
| raise HTTPException(status_code=500, detail={"code": "security_fallback", "message": _public_error_message(500)}) from exc | |
| def api_key_points(): | |
| # Liste melangee pour l'affichage "points cles" non repetitif. | |
| points = list(VALUATION_KEY_POINTS) | |
| random.shuffle(points) | |
| return {"success": True, "points": points} | |
| BASE_DIR = Path(__file__).resolve().parent | |
| STATIC_DIR = BASE_DIR / "static" | |
| if STATIC_DIR.exists(): | |
| # Exposition des assets frontend exportes par Next. | |
| # Important: les chemins doivent correspondre a la structure du build Next export. | |
| for route_path, directory_name, mount_name in [ | |
| ("/assets", "assets", "assets"), | |
| ("/_next", "_next", "next"), | |
| ("/icons", "icons", "icons"), | |
| ]: | |
| target = STATIC_DIR / directory_name | |
| if target.exists(): | |
| app.mount(route_path, StaticFiles(directory=target), name=mount_name) | |
| def serve_spa(full_path: str): | |
| # Fallback SPA: toute route app renvoie index.html. | |
| # Permet le rafraichissement direct des routes App Router cote navigateur. | |
| if not STATIC_DIR.exists(): | |
| raise HTTPException(status_code=404, detail="Frontend static build not found") | |
| def _with_cache_headers(response: FileResponse, target: Path) -> FileResponse: | |
| # Strategie cache: | |
| # - HTML + payloads RSC (.txt) -> no-store pour eviter les incoherences de build/cdn | |
| # - assets hashés (js/css/fonts/images) -> cache long immutable | |
| suffix = target.suffix.lower() | |
| name = target.name.lower() | |
| if suffix in {".html", ".txt"} or name == "index.html": | |
| response.headers["Cache-Control"] = "no-store, max-age=0, must-revalidate" | |
| response.headers["Pragma"] = "no-cache" | |
| response.headers["Expires"] = "0" | |
| elif suffix in {".js", ".css", ".png", ".jpg", ".jpeg", ".webp", ".svg", ".ico", ".woff", ".woff2"}: | |
| response.headers["Cache-Control"] = "public, max-age=31536000, immutable" | |
| return response | |
| candidates: list[Path] = [] | |
| if full_path: | |
| requested = STATIC_DIR / full_path | |
| candidates.append(requested) # /path/to/file.ext | |
| candidates.append(STATIC_DIR / f"{full_path}.html") # /route -> /route.html | |
| candidates.append(STATIC_DIR / full_path / "index.html") # /route -> /route/index.html | |
| for candidate in candidates: | |
| if candidate.exists() and candidate.is_file(): | |
| return _with_cache_headers(FileResponse(candidate), candidate) | |
| index_file = STATIC_DIR / "index.html" | |
| return _with_cache_headers(FileResponse(index_file), index_file) | |