Spaces:
Sleeping
Sleeping
Download app/main.py from jer6/sentiment-api: direct link, hf CLI and curl.
- Browser
- Download file 6.21 kB
-
https://huggingface.co/spaces/jer6/sentiment-api/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/jer6/sentiment-api/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/jer6/sentiment-api/resolve/main/app/main.py
6.21 kB
| import os | |
| from typing import Optional, List | |
| from functools import lru_cache | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, Field | |
| from transformers import pipeline | |
| from langdetect import detect | |
| from .rules import rules_adjustment | |
| import yfinance as yf | |
| from datetime import datetime, timedelta | |
| os.environ.setdefault("HF_HOME", "/models") | |
| XLMR_MODEL = "cardiffnlp/twitter-xlm-roberta-base-sentiment" | |
| MT_MODEL = "Helsinki-NLP/opus-mt-fr-en" | |
| FINBERT_MODEL = "yiyanghkust/finbert-tone" | |
| app = FastAPI(title="Sentiment News API", version="1.0.0") | |
| def stock_history(ticker: str): | |
| try: | |
| end = datetime.now() | |
| start = end - timedelta(days=7) | |
| # Essaye uniquement les places boursières éligibles PEA | |
| suffixes = [".PA", ".AS", ".BR", ".F", ".MI", ".MC", ".LS", ".HE", ".ST"] | |
| data = None | |
| found_ticker = None | |
| for suffix in suffixes: | |
| yf_ticker = ticker if '.' in ticker else f"{ticker}{suffix}" | |
| d = yf.download(yf_ticker, start=start.strftime("%Y-%m-%d"), end=end.strftime("%Y-%m-%d"), interval="1d") | |
| if not d.empty: | |
| data = d | |
| found_ticker = yf_ticker | |
| break | |
| if data is None or data.empty: | |
| raise HTTPException(status_code=404, detail="Aucune donnée trouvée") | |
| # Formatage pour le front | |
| import pandas as pd | |
| def scalar(val): | |
| if isinstance(val, pd.Series): | |
| return val.iloc[0] | |
| return val | |
| series = [ | |
| { | |
| "t": idx.strftime("%Y-%m-%dT%H:%M:%S"), | |
| "price": float(scalar(row["Close"])), | |
| "sentiment": 0.5, # mock | |
| "volumeMentions": int(0 if pd.isna(scalar(row["Volume"])) else scalar(row["Volume"])), | |
| } | |
| for idx, row in data.iterrows() | |
| ] | |
| return {"series": series} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def clip(x: float, lo=-1.0, hi=1.0) -> float: | |
| return max(lo, min(hi, x)) | |
| def get_xlmr(): | |
| return pipeline("sentiment-analysis", model=XLMR_MODEL, tokenizer=XLMR_MODEL) | |
| def get_translator(): | |
| from transformers import MarianMTModel, MarianTokenizer | |
| tok = MarianTokenizer.from_pretrained(MT_MODEL) | |
| mdl = MarianMTModel.from_pretrained(MT_MODEL) | |
| return tok, mdl | |
| def get_finbert(): | |
| return pipeline("sentiment-analysis", model=FINBERT_MODEL, tokenizer=FINBERT_MODEL) | |
| def score_xlmr(text: str) -> float: | |
| if not text: | |
| return 0.0 | |
| clf = get_xlmr() | |
| out = clf(text[:1000], truncation=True)[0] | |
| # CardiffNLP XLM-R returns labels: 'positive', 'neutral', 'negative' | |
| lab2val = {"positive": 1.0, "neutral": 0.0, "negative": -1.0} | |
| label = out["label"].lower() | |
| return lab2val.get(label, 0.0) * float(out["score"]) | |
| def fr2en(text: str) -> str: | |
| tok, mdl = get_translator() | |
| batch = tok([text], return_tensors="pt", truncation=True) | |
| gen = mdl.generate(**batch, max_new_tokens=256) | |
| return tok.decode(gen[0], skip_special_tokens=True) | |
| def score_finbert_via_translation(text_fr: str) -> float: | |
| if not text_fr: | |
| return 0.0 | |
| try: | |
| lang = detect(text_fr) | |
| except Exception: | |
| lang = "fr" | |
| text = text_fr if lang.startswith("en") else fr2en(text_fr) | |
| clf = get_finbert() | |
| out = clf(text[:1000], truncation=True)[0] | |
| lab2val = {"positive": 1.0, "neutral": 0.0, "negative": -1.0} | |
| return lab2val[out["label"].lower()] * float(out["score"]) | |
| class SentimentRequest(BaseModel): | |
| headline: str = Field(..., description="Titre de l'article") | |
| body: Optional[str] = Field(None, description="Corps du texte") | |
| weights: Optional[dict] = Field( | |
| default_factory=lambda: {"finbert": 0.6, "xlmr": 0.4, "headline": 0.7, "body": 0.3}, | |
| description="Poids d'agrégation" | |
| ) | |
| apply_rules: bool = True | |
| class SentimentItem(BaseModel): | |
| headline: str | |
| body: Optional[str] = None | |
| class BatchRequest(BaseModel): | |
| items: List[SentimentItem] | |
| class SentimentResponse(BaseModel): | |
| score: float | |
| breakdown: dict | |
| def root(): | |
| return {"ok": True, "service": "sentiment-news", "version": "1.0.0"} | |
| def healthz(): | |
| # Health check ultra-rapide: ne charge RIEN | |
| return {"ok": True} | |
| def ready(warmup: bool = False): | |
| # Optionnel: forcer le chargement des modèles si ?warmup=1 | |
| if warmup: | |
| _ = get_xlmr(); _ = get_finbert(); _ = get_translator() | |
| return {"ok": True, "models": "loaded"} | |
| return {"ok": True, "models": "skipped"} | |
| def sentiment(req: SentimentRequest): | |
| w_fin, w_xlm = req.weights.get("finbert", 0.6), req.weights.get("xlmr", 0.4) | |
| w_h, w_b = req.weights.get("headline", 0.7), req.weights.get("body", 0.3) | |
| h_x = score_xlmr(req.headline) | |
| h_f = score_finbert_via_translation(req.headline) | |
| h = w_fin * h_f + w_xlm * h_x | |
| b = 0.0 | |
| b_x = b_f = None | |
| if req.body: | |
| b_x = score_xlmr(req.body) | |
| b_f = score_finbert_via_translation(req.body) | |
| b = w_fin * b_f + w_xlm * b_x | |
| score = w_h * h + w_b * b | |
| rules = 0.0 | |
| if req.apply_rules: | |
| rules = rules_adjustment((req.headline or "") + "\n" + (req.body or "")) | |
| score = clip(score + rules) | |
| return SentimentResponse( | |
| score=clip(score), | |
| breakdown={ | |
| "headline": {"xlmr": h_x, "finbert": h_f, "combined": h}, | |
| "body": {"xlmr": b_x if req.body else None, "finbert": b_f if req.body else None, "combined": b if req.body else None}, | |
| "weights": {"finbert": w_fin, "xlmr": w_xlm, "headline": w_h, "body": w_b}, | |
| "rules": rules, | |
| }, | |
| ) | |
| def sentiment_batch(req: BatchRequest): | |
| out = [] | |
| for it in req.items: | |
| single = sentiment(SentimentRequest(headline=it.headline, body=it.body)) | |
| out.append(single.dict()) | |
| return {"results": out} |