File size: 6,031 Bytes
8f8fb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#!/usr/bin/env python3
"""Create the derived FinBERT sentiment file required by generate.py."""

from __future__ import annotations

import argparse
import glob
import json
from datetime import datetime, timezone
from pathlib import Path

import torch
import torch.nn.functional as functional
from transformers import AutoModelForSequenceClassification, AutoTokenizer


MODEL_ID = "ProsusAI/finbert"
CRYPTO_KEYWORDS = {
    "bitcoin": ("bitcoin", "btc"),
    "ethereum": ("ethereum", "eth", "ether"),
    "tether": ("tether", "usdt"),
    "xrp": ("xrp", "ripple"),
    "bnb": ("bnb", "binance coin", "binance"),
}
GENERAL_KEYWORDS = (
    "crypto",
    "cryptocurrency",
    "digital currency",
    "blockchain",
    "defi",
    "digital asset",
    "altcoin",
    "token",
)


def parse_args() -> argparse.Namespace:
    project_root = Path(__file__).resolve().parents[3]
    release_root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input-dir", type=Path, default=project_root / "smdata")
    parser.add_argument(
        "--output",
        type=Path,
        default=release_root / "cache" / "crypto_news_sentiment.json",
    )
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
    parser.add_argument(
        "--local-files-only",
        action="store_true",
        help="Use the already cached tokenizer/model without contacting Hugging Face",
    )
    return parser.parse_args()


def article_text(article: dict) -> str:
    title = article.get("title", "") or article.get("original_content", "")
    full = article.get("full_content", "") or ""
    if len(full) > 50 and not full.startswith(("HTTP", "Could not")):
        return f"{title}. {full[:400]}" if title else full[:500]
    return title


def mentioned_coins(text: str) -> list[str]:
    lowered = text.lower()
    matches = [
        coin
        for coin, keywords in CRYPTO_KEYWORDS.items()
        if any(keyword in lowered for keyword in keywords)
    ]
    if matches:
        return matches
    if any(keyword in lowered for keyword in GENERAL_KEYWORDS):
        return list(CRYPTO_KEYWORDS)
    return list(CRYPTO_KEYWORDS)


def score_articles(articles: list[dict], tokenizer, model, device, batch_size: int) -> list[float]:
    scores = []
    texts = [article_text(article) for article in articles]
    for start in range(0, len(texts), batch_size):
        batch = texts[start : start + batch_size]
        inputs = tokenizer(
            batch,
            padding=True,
            truncation=True,
            max_length=512,
            return_tensors="pt",
        ).to(device)
        with torch.no_grad():
            logits = model(**inputs).logits
        probabilities = functional.softmax(logits, dim=-1)
        scores.extend((probabilities[:, 0] - probabilities[:, 1]).cpu().tolist())
        print(f"Scored {min(start + batch_size, len(texts))}/{len(texts)}", end="\r")
    print()
    return scores


def main() -> None:
    args = parse_args()
    if args.batch_size <= 0:
        raise ValueError("batch size must be positive")
    paths = sorted(Path(path) for path in glob.glob(str(args.input_dir / "crypto_strong_news_*_scored.json")))
    if not paths:
        raise FileNotFoundError(f"No scored news files found in {args.input_dir}")

    articles = []
    seen_articles = set()
    for path in paths:
        with path.open(encoding="utf-8") as handle:
            payload = json.load(handle)
        source_articles = payload if isinstance(payload, list) else payload.get("articles", [])
        for article in source_articles:
            if article.get("language") != "English" or not article_text(article).strip():
                continue
            identity = (
                article.get("timestamp", ""),
                article.get("title", ""),
                article.get("url", ""),
            )
            if identity in seen_articles:
                continue
            seen_articles.add(identity)
            articles.append(article)
    articles.sort(key=lambda article: article.get("timestamp", ""))

    if args.device == "auto":
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    else:
        device = torch.device(args.device)
    print(f"Loading {MODEL_ID} on {device}; {len(articles)} articles")
    tokenizer = AutoTokenizer.from_pretrained(
        MODEL_ID,
        local_files_only=args.local_files_only,
    )
    # FinBERT is published with both .bin and .safetensors weights. Newer
    # Transformers rejects torch.load for older PyTorch versions, so force the
    # safe checkpoint even when the legacy .bin file is also cached.
    model = AutoModelForSequenceClassification.from_pretrained(
        MODEL_ID,
        use_safetensors=True,
        local_files_only=args.local_files_only,
    ).to(device).eval()
    scores = score_articles(articles, tokenizer, model, device, args.batch_size)

    derived = [
        {
            "timestamp": article.get("timestamp", ""),
            "sentiment": round(float(score), 6),
            "coins": mentioned_coins(article_text(article)),
        }
        for article, score in zip(articles, scores)
    ]
    output = {
        "metadata": {
            "model": MODEL_ID,
            "model_revision": getattr(model.config, "_commit_hash", None),
            "score_formula": "P(positive) - P(negative)",
            "generated_at": datetime.now(timezone.utc).isoformat(),
            "article_count": len(derived),
            "contains_article_text": False,
        },
        "articles": derived,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("w", encoding="utf-8") as handle:
        json.dump(output, handle, ensure_ascii=False, allow_nan=False)
        handle.write("\n")
    print(f"Wrote {len(derived)} derived records to {args.output}")


if __name__ == "__main__":
    main()