Sasmita Harini commited on
Commit
634db4b
·
1 Parent(s): a1e7f9d

Run FastAPI as subprocess in app.py

Browse files
Files changed (1) hide show
  1. api.py +0 -82
api.py DELETED
@@ -1,82 +0,0 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel
3
- import utils
4
- from deep_translator import GoogleTranslator
5
- from gtts import gTTS
6
- import base64
7
- import io
8
- import json
9
- import uvicorn
10
- import logging
11
-
12
- logging.basicConfig(level=logging.INFO)
13
- logger = logging.getLogger(__name__)
14
-
15
- app = FastAPI(title="News Analysis API")
16
- translator = GoogleTranslator(source='en', target='hi')
17
-
18
- class CompanyRequest(BaseModel):
19
- company_name: str
20
-
21
- @app.post("/api/fetch_news")
22
- async def fetch_news(request: CompanyRequest):
23
- try:
24
- company_name = request.company_name.strip().lower()
25
- if not company_name:
26
- raise HTTPException(status_code=400, detail="Company name is required")
27
-
28
- logger.info(f"Fetching news for {company_name}")
29
- file_name = utils.fetch_and_save_news(company_name)
30
- if not file_name:
31
- logger.warning(f"No news found for {company_name}")
32
- raise HTTPException(status_code=404, detail=f"No news found for {company_name}")
33
-
34
- with open(file_name, "r", encoding="utf-8") as file:
35
- content = file.read()
36
-
37
- try:
38
- news_data = json.loads(content) # Should work with updated utils.py
39
- logger.info(f"Successfully parsed news data for {company_name}")
40
- return news_data
41
- except json.JSONDecodeError as e:
42
- logger.error(f"JSON parsing failed: {str(e)}", exc_info=True)
43
- raise HTTPException(status_code=500, detail=f"Error parsing JSON: {str(e)}")
44
-
45
- except Exception as e:
46
- logger.error(f"Error in fetch_news: {str(e)}", exc_info=True)
47
- raise HTTPException(status_code=500, detail=f"Error fetching news: {str(e)}")
48
-
49
- @app.post("/api/text_to_speech")
50
- async def text_to_speech(request: CompanyRequest):
51
- try:
52
- company_name = request.company_name.strip().lower()
53
- if not company_name:
54
- raise HTTPException(status_code=400, detail="Company name is required")
55
-
56
- file_name = f"{company_name}_news.txt"
57
- try:
58
- with open(file_name, "r", encoding="utf-8") as file:
59
- news_data = json.load(file)
60
- sentiment_text = news_data.get("Final Sentiment Analysis", "")
61
- if not sentiment_text:
62
- raise HTTPException(status_code=404, detail="Sentiment analysis not found")
63
-
64
- hindi_text = translator.translate(sentiment_text)
65
- tts = gTTS(text=hindi_text, lang='hi')
66
- mp3_fp = io.BytesIO()
67
- tts.write_to_fp(mp3_fp)
68
- mp3_fp.seek(0)
69
- audio_base64 = base64.b64encode(mp3_fp.read()).decode('utf-8')
70
- return {"text": hindi_text, "audio_base64": audio_base64}
71
- except FileNotFoundError:
72
- raise HTTPException(status_code=404, detail=f"News file for {company_name} not found")
73
- except Exception as e:
74
- logger.error(f"Error in text_to_speech: {str(e)}", exc_info=True)
75
- raise HTTPException(status_code=500, detail=f"Error generating speech: {str(e)}")
76
-
77
- @app.get("/api/health")
78
- async def health_check():
79
- return {"status": "healthy"}
80
-
81
- if __name__ == "__main__":
82
- uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True)