jer6 commited on
Commit
45fabd7
·
verified ·
1 Parent(s): a1c142f

Upload 7 files

Browse files
Files changed (7) hide show
  1. Dockerfile +42 -0
  2. README.md +1 -11
  3. app/__init__.py +0 -0
  4. app/main.py +148 -0
  5. app/rules.py +25 -0
  6. docker-compose.yml +20 -0
  7. requirements.txt +8 -0
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+
4
+ # Dépendances système minimales
5
+ RUN apt-get update && apt-get install -y --no-install-recommends \
6
+ git \
7
+ && rm -rf /var/lib/apt/lists/*
8
+
9
+
10
+ ENV PYTHONDONTWRITEBYTECODE=1 \
11
+ PYTHONUNBUFFERED=1 \
12
+ TRANSFORMERS_CACHE=/models \
13
+ HF_HOME=/models
14
+
15
+
16
+ WORKDIR /app
17
+ COPY requirements.txt ./
18
+ RUN pip install --no-cache-dir -r requirements.txt
19
+
20
+
21
+ # Pré-téléchargement des modèles pour éviter le cold start
22
+ RUN python - <<'PY'
23
+ from transformers import pipeline
24
+ from transformers import MarianMTModel, MarianTokenizer
25
+
26
+
27
+ print('Downloading XLM-R sentiment...')
28
+ pipeline('sentiment-analysis', model='cardiffnlp/twitter-xlm-roberta-base-sentiment')
29
+ print('Downloading FinBERT...')
30
+ pipeline('sentiment-analysis', model='yiyanghkust/finbert-tone')
31
+ print('Downloading Marian FR-EN...')
32
+ MarianTokenizer.from_pretrained('Helsinki-NLP/opus-mt-fr-en')
33
+ MarianMTModel.from_pretrained('Helsinki-NLP/opus-mt-fr-en')
34
+ print('All models cached.')
35
+ PY
36
+
37
+
38
+ COPY app ./app
39
+ EXPOSE 8000
40
+
41
+
42
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
README.md CHANGED
@@ -1,11 +1 @@
1
- ---
2
- title: Sentiment Api
3
- emoji: 🌖
4
- colorFrom: green
5
- colorTo: red
6
- sdk: docker
7
- pinned: false
8
- short_description: sentiment-api
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ # test-sentiment
 
 
 
 
 
 
 
 
 
 
app/__init__.py ADDED
File without changes
app/main.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from typing import Optional, List
4
+ from functools import lru_cache
5
+ from fastapi import FastAPI
6
+ from pydantic import BaseModel, Field
7
+ from transformers import pipeline
8
+ from langdetect import detect
9
+ from .rules import rules_adjustment
10
+
11
+ os.environ.setdefault("TRANSFORMERS_CACHE", "/models")
12
+
13
+ XLMR_MODEL = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
14
+ MT_MODEL = "Helsinki-NLP/opus-mt-fr-en"
15
+ FINBERT_MODEL = "yiyanghkust/finbert-tone"
16
+
17
+ app = FastAPI(title="Sentiment News API", version="1.0.0")
18
+
19
+ def clip(x: float, lo=-1.0, hi=1.0) -> float:
20
+ return max(lo, min(hi, x))
21
+
22
+ @lru_cache(maxsize=1)
23
+ def get_xlmr():
24
+ return pipeline("sentiment-analysis", model=XLMR_MODEL, tokenizer=XLMR_MODEL)
25
+
26
+ @lru_cache(maxsize=1)
27
+ def get_translator():
28
+ from transformers import MarianMTModel, MarianTokenizer
29
+ tok = MarianTokenizer.from_pretrained(MT_MODEL)
30
+ mdl = MarianMTModel.from_pretrained(MT_MODEL)
31
+ return tok, mdl
32
+
33
+ @lru_cache(maxsize=1)
34
+ def get_finbert():
35
+ return pipeline("sentiment-analysis", model=FINBERT_MODEL, tokenizer=FINBERT_MODEL)
36
+
37
+ def score_xlmr(text: str) -> float:
38
+ if not text:
39
+ return 0.0
40
+ clf = get_xlmr()
41
+ out = clf(text[:1000], truncation=True)[0]
42
+ # CardiffNLP XLM-R returns labels: 'positive', 'neutral', 'negative'
43
+ lab2val = {"positive": 1.0, "neutral": 0.0, "negative": -1.0}
44
+ label = out["label"].lower()
45
+ return lab2val.get(label, 0.0) * float(out["score"])
46
+
47
+ def fr2en(text: str) -> str:
48
+ tok, mdl = get_translator()
49
+ batch = tok([text], return_tensors="pt", truncation=True)
50
+ gen = mdl.generate(**batch, max_new_tokens=256)
51
+ return tok.decode(gen[0], skip_special_tokens=True)
52
+
53
+ def score_finbert_via_translation(text_fr: str) -> float:
54
+ if not text_fr:
55
+ return 0.0
56
+ try:
57
+ lang = detect(text_fr)
58
+ except Exception:
59
+ lang = "fr"
60
+ text = text_fr if lang.startswith("en") else fr2en(text_fr)
61
+ clf = get_finbert()
62
+ out = clf(text[:1000], truncation=True)[0]
63
+ lab2val = {"positive": 1.0, "neutral": 0.0, "negative": -1.0}
64
+ return lab2val[out["label"].lower()] * float(out["score"])
65
+
66
+
67
+
68
+ class SentimentRequest(BaseModel):
69
+ headline: str = Field(..., description="Titre de l'article")
70
+ body: Optional[str] = Field(None, description="Corps du texte")
71
+ weights: Optional[dict] = Field(
72
+ default_factory=lambda: {"finbert": 0.6, "xlmr": 0.4, "headline": 0.7, "body": 0.3},
73
+ description="Poids d'agrégation"
74
+ )
75
+ apply_rules: bool = True
76
+
77
+ class SentimentItem(BaseModel):
78
+ headline: str
79
+ body: Optional[str] = None
80
+
81
+ class BatchRequest(BaseModel):
82
+ items: List[SentimentItem]
83
+
84
+ class SentimentResponse(BaseModel):
85
+ score: float
86
+ breakdown: dict
87
+
88
+ @app.get("/")
89
+ def root():
90
+ return {"ok": True, "service": "sentiment-news", "version": "1.0.0"}
91
+
92
+ @app.get("/healthz")
93
+ def healthz():
94
+ # Health check ultra-rapide: ne charge RIEN
95
+ return {"ok": True}
96
+
97
+ @app.get("/ready")
98
+ def ready(warmup: bool = False):
99
+ # Optionnel: forcer le chargement des modèles si ?warmup=1
100
+ if warmup:
101
+ _ = get_xlmr(); _ = get_finbert(); _ = get_translator()
102
+ return {"ok": True, "models": "loaded"}
103
+ return {"ok": True, "models": "skipped"}
104
+
105
+
106
+
107
+ @app.post("/sentiment", response_model=SentimentResponse)
108
+ def sentiment(req: SentimentRequest):
109
+ w_fin, w_xlm = req.weights.get("finbert", 0.6), req.weights.get("xlmr", 0.4)
110
+ w_h, w_b = req.weights.get("headline", 0.7), req.weights.get("body", 0.3)
111
+
112
+ h_x = score_xlmr(req.headline)
113
+ h_f = score_finbert_via_translation(req.headline)
114
+ h = w_fin * h_f + w_xlm * h_x
115
+
116
+ b = 0.0
117
+ b_x = b_f = None
118
+ if req.body:
119
+ b_x = score_xlmr(req.body)
120
+ b_f = score_finbert_via_translation(req.body)
121
+ b = w_fin * b_f + w_xlm * b_x
122
+
123
+ score = w_h * h + w_b * b
124
+
125
+ rules = 0.0
126
+ if req.apply_rules:
127
+ rules = rules_adjustment((req.headline or "") + "\n" + (req.body or ""))
128
+ score = clip(score + rules)
129
+
130
+ return SentimentResponse(
131
+ score=clip(score),
132
+ breakdown={
133
+ "headline": {"xlmr": h_x, "finbert": h_f, "combined": h},
134
+ "body": {"xlmr": b_x if req.body else None, "finbert": b_f if req.body else None, "combined": b if req.body else None},
135
+ "weights": {"finbert": w_fin, "xlmr": w_xlm, "headline": w_h, "body": w_b},
136
+ "rules": rules,
137
+ },
138
+ )
139
+
140
+
141
+
142
+ @app.post("/sentiment/batch")
143
+ def sentiment_batch(req: BatchRequest):
144
+ out = []
145
+ for it in req.items:
146
+ single = sentiment(SentimentRequest(headline=it.headline, body=it.body))
147
+ out.append(single.dict())
148
+ return {"results": out}
app/rules.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ POSITIVE_BOOSTS = [
2
+ "relève ses prévisions", "relève sa guidance", "bat le consensus",
3
+ "au-dessus des attentes", "meilleur que prévu", "rachat d'actions",
4
+ "dividende relevé", "rehausse", "relever ses perspectives",
5
+ ]
6
+
7
+
8
+ NEGATIVE_BOOSTS = [
9
+ "abaisse ses prévisions", "abaisse sa guidance", "en dessous des attentes",
10
+ "profit warning", "avertissement sur résultats", "émission d'actions",
11
+ "enquête du régulateur", "enquête de la sec", "abaisse ses perspectives",
12
+ ]
13
+
14
+
15
+ def rules_adjustment(text: str) -> float:
16
+ t = (text or "").lower()
17
+ score = 0.0
18
+ for kw in POSITIVE_BOOSTS:
19
+ if kw in t:
20
+ score += 0.15
21
+ for kw in NEGATIVE_BOOSTS:
22
+ if kw in t:
23
+ score -= 0.20
24
+ # clip
25
+ return max(-0.4, min(0.4, score))
docker-compose.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.9"
2
+ services:
3
+ sentiment:
4
+ build: .
5
+ image: sentiment-service:latest
6
+ container_name: sentiment-service
7
+ ports:
8
+ - "8000:8000"
9
+ environment:
10
+ - TRANSFORMERS_CACHE=/models
11
+ - HF_HOME=/models
12
+ volumes:
13
+ - models-cache:/models
14
+ deploy:
15
+ resources:
16
+ limits:
17
+ cpus: "2.0"
18
+ memory: 4g
19
+ volumes:
20
+ models-cache:
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.115.2
2
+ uvicorn[standard]==0.30.6
3
+ transformers==4.44.2
4
+ torch==2.3.1
5
+ sentencepiece==0.2.0
6
+ sacremoses==0.1.1
7
+ langdetect==1.0.9
8
+ protobuf