File size: 1,724 Bytes
5fca79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

# Load models once on startup
try:
    ner_model = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple")
    sentiment_model = pipeline("sentiment-analysis", model="ProsusAI/finbert")
except Exception as e:
    logger.error(f"Model loading failed: {e}")
    ner_model = None
    sentiment_model = None

class TextRequest(BaseModel):
    text: str

@app.get("/")
def home():
    return {"message": "Crypto News API is alive!"}

@app.post("/sentiment")
def analyze_sentiment(req: TextRequest):
    if not sentiment_model:
        raise HTTPException(status_code=503, detail="Sentiment model not available")
    text = req.text
    if not text:
        raise HTTPException(status_code=400, detail="Text cannot be empty")
    result = sentiment_model(text[:512])[0]
    return {
        "label": result["label"],
        "score": round(result["score"] * 100, 2)
    }

@app.post("/ner")
def analyze_ner(req: TextRequest):
    if not ner_model:
        raise HTTPException(status_code=503, detail="NER model not available")
    text = req.text
    if not text:
        raise HTTPException(status_code=400, detail="Text cannot be empty")
    entities = ner_model(text[:512])
    # Filter relevant entities (ORG, PERSON, MISC, PRODUCT, GPE)
    relevant = [e['word'] for e in entities if e['entity_group'] in ['ORG', 'PERSON', 'MISC', 'PRODUCT', 'GPE']]
    # Remove duplicates and limit to 5
    unique_entities = list(dict.fromkeys(relevant))[:5]
    return {"entities": unique_entities}