Sasmita Harini commited on
Commit
1da5140
·
1 Parent(s): 3a8facb

Run FastAPI as subprocess in app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -50
app.py CHANGED
@@ -3,62 +3,118 @@ import requests
3
  import json
4
  import base64
5
  import io
6
- import subprocess
7
- import time
8
- import os
9
 
10
- API_BASE_URL = "http://localhost:8000/api"
 
11
 
12
- # Start FastAPI server in the background
13
- if "fastapi_process" not in st.session_state:
14
- # Ensure api.py is in the same directory
15
- process = subprocess.Popen(["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"],
16
- stdout=subprocess.PIPE, stderr=subprocess.PIPE)
17
- st.session_state["fastapi_process"] = process
18
- time.sleep(3) # Give FastAPI time to start
19
-
20
- st.title("News Summarization App")
21
 
 
22
  company_name = st.text_input("Enter the company name:", "").strip().lower()
23
 
24
  if st.button("Fetch News"):
25
  if company_name:
26
- status = st.status("Fetching news...", expanded=True)
27
- status.write(f"Fetching news for **{company_name}**...")
28
- try:
29
- response = requests.post(
30
- f"{API_BASE_URL}/fetch_news",
31
- json={"company_name": company_name},
32
- timeout=120
33
- )
34
- response.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- news_data = response.json()
37
- if not news_data or "Company" not in news_data:
38
- status.update(label="No news found", state="error")
39
- st.warning(f"No news found for {company_name}")
40
- else:
41
- status.update(label="News fetched successfully!", state="complete", expanded=False)
42
- st.subheader(f"News Analysis for {news_data['Company']}")
43
- # ... rest of your display logic ...
44
-
45
- except requests.exceptions.RequestException as e:
46
- status.update(label="Connection error", state="error")
47
- st.error(f"Error connecting to API: {str(e)}")
48
- st.info("Check if the FastAPI backend is running correctly.")
49
- except json.JSONDecodeError:
50
- status.update(label="Invalid response", state="error")
51
- st.error("Received invalid data from the API")
52
- except Exception as e:
53
- status.update(label="Processing error", state="error")
54
- st.error(f"Error processing news data: {str(e)}")
55
  else:
56
- st.warning("Please enter a company name.")
57
-
58
- # Optional: Cleanup on app shutdown (not guaranteed in Spaces)
59
- def cleanup():
60
- if "fastapi_process" in st.session_state:
61
- st.session_state["fastapi_process"].terminate()
62
-
63
- import atexit
64
- atexit.register(cleanup)
 
3
  import json
4
  import base64
5
  import io
6
+ from deep_translator import GoogleTranslator
7
+ from gtts import gTTS
8
+ import utils
9
 
10
+ # Initialize translator
11
+ translator = GoogleTranslator(source='en', target='hi')
12
 
13
+ # Streamlit app
14
+ st.title("News Summarization and Text-to-Speech Application")
 
 
 
 
 
 
 
15
 
16
+ # User input for company name
17
  company_name = st.text_input("Enter the company name:", "").strip().lower()
18
 
19
  if st.button("Fetch News"):
20
  if company_name:
21
+ with st.status("Fetching news...", expanded=True) as status:
22
+ st.write(f"Fetching news for **{company_name}**...")
23
+
24
+ try:
25
+ # Call the utils function directly
26
+ file_name = utils.fetch_and_save_news(company_name)
27
+
28
+ if not file_name:
29
+ status.update(label="No news found", state="error")
30
+ st.warning(f"No news found for {company_name}")
31
+ else:
32
+ # Read the saved JSON file
33
+ with open(file_name, "r", encoding="utf-8") as file:
34
+ news_data = json.load(file)
35
+
36
+ status.update(label="News fetched successfully!", state="complete", expanded=False)
37
+
38
+ # Display news data
39
+ st.subheader(f"News Analysis for {news_data['Company']}")
40
+
41
+ # Articles section
42
+ st.subheader("Articles")
43
+ with st.expander("View Articles", expanded=False):
44
+ for i, article in enumerate(news_data['Articles']):
45
+ st.markdown(f"#### Article {i+1}: {article['Title']}")
46
+ st.markdown(f"**Summary:** {article['Summary']}")
47
+ st.markdown(f"**Sentiment:** {article['Sentiment']}")
48
+ st.markdown(f"**Topics:** {', '.join(article['Topics'])}")
49
+ st.divider()
50
+
51
+ # Sentiment Distribution
52
+ st.subheader("Sentiment Distribution")
53
+ sentiment_data = news_data['Comparative Sentiment Score']['Sentiment Distribution']
54
+ col1, col2, col3 = st.columns(3)
55
+ col1.metric("Positive", sentiment_data['Positive'])
56
+ col2.metric("Neutral", sentiment_data['Neutral'])
57
+ col3.metric("Negative", sentiment_data['Negative'])
58
+
59
+ # Topic Analysis
60
+ st.subheader("Topic Analysis")
61
+ with st.expander("View Topic Analysis", expanded=False):
62
+ st.markdown("**Common Topics:**")
63
+ st.write(", ".join(news_data['Topic Overlap']['Common Topics']))
64
+ for key, value in news_data['Topic Overlap'].items():
65
+ if key != "Common Topics":
66
+ st.markdown(f"**{key}:**")
67
+ st.write(", ".join(value))
68
+
69
+ # Coverage Differences
70
+ st.subheader("Coverage Differences")
71
+ with st.expander("View Comparative Analysis", expanded=False):
72
+ coverage_diff = news_data['Coverage Differences']
73
+ if isinstance(coverage_diff, str):
74
+ st.write(coverage_diff) # Fallback for error cases
75
+ else:
76
+ formatted_text = '"Coverage Differences": [\n'
77
+ for i, item in enumerate(coverage_diff.get("Coverage Differences", [])):
78
+ formatted_text += "{\n"
79
+ formatted_text += f' "Comparison": "{item["Comparison"]}",\n'
80
+ formatted_text += f' "Impact": "{item["Impact"]}"\n'
81
+ formatted_text += "}" + (",\n" if i < len(coverage_diff["Coverage Differences"]) - 1 else "\n")
82
+ formatted_text += "]"
83
+ st.code(formatted_text, language="json")
84
+
85
+ # Final Sentiment Analysis
86
+ st.subheader("Final Sentiment Analysis")
87
+ st.info(news_data['Final Sentiment Analysis'])
88
+
89
+ # Download JSON
90
+ st.subheader("Download Data")
91
+ st.download_button(
92
+ label="Download JSON File",
93
+ data=json.dumps(news_data, indent=4),
94
+ file_name=f"{company_name}_news.json",
95
+ mime="application/json"
96
+ )
97
+
98
+ # Hindi Audio
99
+ st.subheader("Hindi Audio for Final Sentiment Analysis")
100
+ try:
101
+ hindi_text = translator.translate(news_data['Final Sentiment Analysis'])
102
+ tts = gTTS(text=hindi_text, lang='hi')
103
+ audio_io = io.BytesIO()
104
+ tts.write_to_fp(audio_io)
105
+ audio_io.seek(0)
106
+ audio_bytes = audio_io.read()
107
+ st.download_button(
108
+ label="Download Hindi Audio",
109
+ data=audio_bytes,
110
+ file_name=f"{company_name}_sentiment_hindi.mp3",
111
+ mime="audio/mp3"
112
+ )
113
+ except Exception as e:
114
+ st.error(f"Error generating Hindi audio: {str(e)}")
115
 
116
+ except Exception as e:
117
+ status.update(label="Processing error", state="error")
118
+ st.error(f"Error processing news data: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  else:
120
+ st.warning("Please enter a company name.")