Miruzen commited on
Commit
582d6a0
ยท
verified ยท
1 Parent(s): de9911d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -88
app.py CHANGED
@@ -2,62 +2,43 @@ from fastapi import FastAPI
2
  from pydantic import BaseModel
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
4
  import torch
5
- import logging
6
 
7
- # ===============================
8
- # ๐Ÿ”ง Logging setup
9
- # ===============================
10
- logging.basicConfig(level=logging.INFO)
11
- logger = logging.getLogger("forex-sentiment")
12
-
13
- app = FastAPI(title="Forex Sentiment API", version="2.0")
14
 
15
  # ===============================
16
- # ๐Ÿš€ Model configuration
17
  # ===============================
18
- FINBERT_MODEL = "ProsusAI/finbert"
19
- LONGFORMER_MODEL = "Miruzen/LongFormer_Skripsi"
20
 
21
  device = 0 if torch.cuda.is_available() else -1
22
- logger.info(f"๐Ÿง  Using device: {'GPU' if device == 0 else 'CPU'}")
23
 
24
- # ===============================
25
- # ๐Ÿ“ฆ Load Models
26
- # ===============================
27
- logger.info("๐Ÿ“ฅ Loading FinBERT model...")
28
  finbert = pipeline(
29
  "text-classification",
30
- model=FINBERT_MODEL,
31
- tokenizer=FINBERT_MODEL,
32
  return_all_scores=True,
33
- device=device
34
  )
35
 
36
- logger.info("๐Ÿ“ฅ Loading LongFormer model...")
37
  longformer = pipeline(
38
  "text-classification",
39
- model=LONGFORMER_MODEL,
40
- tokenizer=LONGFORMER_MODEL,
41
  return_all_scores=True,
42
- device=device
43
  )
44
 
45
- logger.info("โœ… Models loaded successfully!")
46
 
47
-
48
- # ===============================
49
- # ๐Ÿงพ Input Schema
50
- # ===============================
51
  class InputData(BaseModel):
52
  title: str | None = None
53
  content: str | None = None
54
 
55
 
56
- # ===============================
57
- # ๐Ÿงฉ Helper Functions
58
- # ===============================
59
  def extract_scores(predictions):
60
- """Convert pipeline output into standardized sentiment dict"""
61
  scores = {"positive": 0.0, "neutral": 0.0, "negative": 0.0}
62
  for item in predictions[0]:
63
  label = item["label"].lower()
@@ -67,67 +48,39 @@ def extract_scores(predictions):
67
  scores["negative"] = item["score"]
68
  elif "neu" in label:
69
  scores["neutral"] = item["score"]
 
 
70
 
71
- sentiment = max(scores, key=scores.get)
72
- return {"label": sentiment, "scores": scores}
73
 
74
-
75
- # ===============================
76
- # ๐Ÿ” Main Endpoint
77
- # ===============================
78
  @app.post("/analyze")
79
  def analyze(data: InputData):
80
- logger.info(f"๐Ÿ“ฐ Incoming request: title='{data.title}' | content='{data.content}'")
81
-
82
- result = {}
83
- errors = []
84
-
85
- try:
86
- if data.title:
87
- logger.info("โš™๏ธ Analyzing title with FinBERT...")
88
- finbert_out = finbert(data.title)
89
- result["title"] = extract_scores(finbert_out)
90
- else:
91
- result["title"] = None
92
-
93
- if data.content:
94
- logger.info("โš™๏ธ Analyzing content with LongFormer...")
95
- longformer_out = longformer(data.content)
96
- result["content"] = extract_scores(longformer_out)
97
- else:
98
- result["content"] = None
99
-
100
- # ๐Ÿงฎ Mood score sederhana
101
- mood_score = (
102
- (result.get("title", {}).get("scores", {}).get("positive", 0) +
103
- result.get("content", {}).get("scores", {}).get("positive", 0))
104
- - (result.get("title", {}).get("scores", {}).get("negative", 0) +
105
- result.get("content", {}).get("scores", {}).get("negative", 0))
106
- )
107
-
108
- logger.info("โœ… Analysis completed successfully")
109
-
110
- return {
111
- "title": result.get("title"),
112
- "content": result.get("content"),
113
- "mood_score": mood_score,
114
- "status": "ok"
115
- }
116
-
117
- except Exception as e:
118
- logger.exception("โŒ Error during sentiment analysis")
119
- errors.append(str(e))
120
- return {
121
- "title": None,
122
- "content": None,
123
- "errors": errors,
124
- "status": "error"
125
- }
126
 
127
 
128
- # ===============================
129
- # ๐Ÿฉต Health Check
130
- # ===============================
131
  @app.get("/")
132
  def root():
133
- return {"message": "โœ… Forex Sentiment API active and ready!"}
 
2
  from pydantic import BaseModel
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
4
  import torch
 
5
 
6
+ app = FastAPI(title="Forex Sentiment API", version="1.0")
 
 
 
 
 
 
7
 
8
  # ===============================
9
+ # Load Models
10
  # ===============================
11
+ finbert_name = "ProsusAI/finbert"
12
+ longformer_name = "Miruzen/LongFormer_Skripsi"
13
 
14
  device = 0 if torch.cuda.is_available() else -1
 
15
 
16
+ print("๐Ÿ“ฅ Loading FinBERT model...")
 
 
 
17
  finbert = pipeline(
18
  "text-classification",
19
+ model=finbert_name,
20
+ tokenizer=finbert_name,
21
  return_all_scores=True,
22
+ device=device,
23
  )
24
 
25
+ print("๐Ÿ“ฅ Loading LongFormer model...")
26
  longformer = pipeline(
27
  "text-classification",
28
+ model=longformer_name,
29
+ tokenizer=longformer_name,
30
  return_all_scores=True,
31
+ device=device,
32
  )
33
 
 
34
 
 
 
 
 
35
  class InputData(BaseModel):
36
  title: str | None = None
37
  content: str | None = None
38
 
39
 
 
 
 
40
  def extract_scores(predictions):
41
+ """Convert HF model output into {positive, neutral, negative} dict."""
42
  scores = {"positive": 0.0, "neutral": 0.0, "negative": 0.0}
43
  for item in predictions[0]:
44
  label = item["label"].lower()
 
48
  scores["negative"] = item["score"]
49
  elif "neu" in label:
50
  scores["neutral"] = item["score"]
51
+ dominant = max(scores, key=scores.get)
52
+ return {"label": dominant, "scores": scores}
53
 
 
 
54
 
 
 
 
 
55
  @app.post("/analyze")
56
  def analyze(data: InputData):
57
+ title_result, content_result = None, None
58
+
59
+ if data.title:
60
+ finbert_out = finbert(data.title)
61
+ title_result = extract_scores(finbert_out)
62
+
63
+ if data.content:
64
+ longformer_out = longformer(data.content)
65
+ content_result = extract_scores(longformer_out)
66
+
67
+ mood_score = (
68
+ (title_result["scores"].get("positive", 0) if title_result else 0)
69
+ + (content_result["scores"].get("positive", 0) if content_result else 0)
70
+ - (title_result["scores"].get("negative", 0) if title_result else 0)
71
+ - (content_result["scores"].get("negative", 0) if content_result else 0)
72
+ )
73
+
74
+ return {
75
+ "status": "ok",
76
+ "mood_score": mood_score,
77
+ "details": { # ๐Ÿ”น <โ”€โ”€ inilah kunci penting yang ditunggu Supabase!
78
+ "title": title_result,
79
+ "content": content_result,
80
+ },
81
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
 
 
 
 
84
  @app.get("/")
85
  def root():
86
+ return {"message": "Forex Sentiment API active!"}