File size: 1,652 Bytes
dde1233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89b8097
 
 
dde1233
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from transformers import pipeline
from pydantic import BaseModel
import nest_asyncio
#from pyngrok import ngrok
from fastapi.responses import RedirectResponse

app = FastAPI()

# Load the model
text_classifier = pipeline("text-classification", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")

# Input data model
class TextInput(BaseModel):
    text: str

@app.post('/analyze')
async def Predict_Sentiment(text_input: TextInput):
    text = text_input.text

    # Validate input text
    if not text.strip():  # Check if text is empty or contains only whitespace
        raise HTTPException(status_code=400, detail="Input text is empty or contains only whitespace.")
    elif text.strip() == "--":  # Check if text is "--"
        raise HTTPException(status_code=400, detail="Invalid input text.")
    elif text.isdigit():  # Check if text contains only digits
        raise HTTPException(status_code=400, detail="Input text contains only digits.")
    elif not any(c.isalpha() for c in text):  # Check if text contains any alphabetic characters
        raise HTTPException(status_code=400, detail="Input text contains no alphabetic characters.")

    # Perform sentiment analysis
    try:
        return text_classifier(text)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get('/')
async def home():
    #return "Welcome to Financial Sentiment Analysis API"
    return RedirectResponse(url="/docs")


#ngrok_tunnel = ngrok.connect(8000)
#print('Public URL:', ngrok_tunnel.public_url)
nest_asyncio.apply()
#uvicorn.run(app, port=8000)