huggingapi / app.py
CRYPTONEWS34's picture
Added FastAPI app
5fca79f
raw
history blame
1.72 kB
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}