KatGaw commited on
Commit
34cbc00
β€’
1 Parent(s): f644970
Files changed (1) hide show
  1. app.py +103 -21
app.py CHANGED
@@ -5,36 +5,118 @@ from tools import sentiment_analysis_util
5
  import numpy as np
6
  from dotenv import load_dotenv
7
  import os
8
- st.title("πŸ’¬ Chatbot")
9
- st.caption("")
10
 
 
 
 
11
 
12
- openai_api_key = os.environ["OPENAI_API_KEY"]
13
- # Initialize session state for storing messages if it doesn't already exist
 
 
 
 
 
14
  if "messages" not in st.session_state:
15
- st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
 
 
16
 
17
  # Display all previous messages
18
  for msg in st.session_state.messages:
19
  st.chat_message(msg["role"]).write(msg["content"])
20
 
21
- # Input for new prompts
22
- prompt = st.chat_input("Enter your question:")
23
- if prompt:
24
- if not openai_api_key:
25
- st.error("No OpenAI API key found. Please set the OPENAI_API_KEY environment variable.")
26
- st.stop()
 
27
 
28
- # Append the new user message to session state
 
 
 
29
  st.session_state.messages.append({"role": "user", "content": prompt})
30
- st.chat_message("user").write(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- # Use a spinner to indicate that the model is generating a response
33
- with st.spinner('Thinking...'):
34
- client = OpenAI(api_key=openai_api_key)
35
- response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
36
- msg = response.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- # Append and display the assistant's response
39
- st.session_state.messages.append({"role": "assistant", "content": msg})
40
- st.chat_message("assistant").write(msg)
 
5
  import numpy as np
6
  from dotenv import load_dotenv
7
  import os
 
 
8
 
9
+ st.set_page_config(page_title="LangChain Agent", layout="wide")
10
+ load_dotenv()
11
+ OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
12
 
13
+ llm = ChatOpenAI(model="gpt-3.5-turbo")
14
+
15
+ from langchain_core.runnables import RunnableConfig
16
+
17
+ st.title("πŸ’¬ ExpressMood")
18
+
19
+ #@st.cache_resource
20
  if "messages" not in st.session_state:
21
+ st.session_state["messages"] = [{"role":"system", "content":"""
22
+ You are a sentiment analysis expert. Answer all questions related to the topic. Say I don't know if you don't know.
23
+ """}]
24
 
25
  # Display all previous messages
26
  for msg in st.session_state.messages:
27
  st.chat_message(msg["role"]).write(msg["content"])
28
 
29
+ #initialize_session_state()
30
+
31
+ st.image('el_pic.png')
32
+
33
+ sideb=st.sidebar
34
+ with st.sidebar:
35
+ prompt=st.text_input("Enter topic for sentiment analysis: ")
36
 
37
+ check1=sideb.button(f"analyze {prompt}")
38
+
39
+ if check1:
40
+ # Add user message to chat history
41
  st.session_state.messages.append({"role": "user", "content": prompt})
42
+ # Display user message in chat message container
43
+ with st.chat_message("user"):
44
+ st.markdown(prompt)
45
+
46
+ # ========================== Sentiment analysis
47
+ #Perform sentiment analysis on the cryptocurrency news & predict dominant sentiment along with plotting the sentiment breakdown chart
48
+ # Downloading from reddit
49
+
50
+ # Downloading from alpaca
51
+ if len(prompt.split(' '))<2:
52
+ print('here')
53
+ st.write('I am analyzing Google News ...')
54
+ news_articles = sentiment_analysis_util.fetch_news(str(prompt))
55
+ st.write('Now, I am analyzing Reddit ...')
56
+ reddit_news_articles=sentiment_analysis_util.fetch_reddit_news(prompt)
57
+ analysis_results = []
58
+
59
+ #Perform sentiment analysis for each product review
60
+ if len(prompt.split(' '))<2:
61
+ print('here')
62
+ for article in news_articles:
63
+ if prompt.lower()[0:6] in article['News_Article'].lower():
64
+ sentiment_analysis_result = sentiment_analysis_util.analyze_sentiment(article['News_Article'])
65
 
66
+ # Display sentiment analysis results
67
+ #print(f'News Article: {sentiment_analysis_result["News_Article"]} : Sentiment: {sentiment_analysis_result["Sentiment"]}', '\n')
68
+
69
+ result = {
70
+ 'News_Article': sentiment_analysis_result["News_Article"],
71
+ 'Sentiment': sentiment_analysis_result["Sentiment"][0]['label'],
72
+ 'Index': sentiment_analysis_result["Sentiment"][0]['score'],
73
+ 'URL': article['URL']
74
+ }
75
+
76
+ analysis_results.append(result)
77
+
78
+ articles_url=[]
79
+ for article in reddit_news_articles:
80
+ if prompt.lower()[0:6] in article.lower():
81
+ sentiment_analysis_result_reddit = sentiment_analysis_util.analyze_sentiment(article)
82
+
83
+ # Display sentiment analysis results
84
+ #print(f'News Article: {sentiment_analysis_result_reddit["News_Article"]} : Sentiment: {sentiment_analysis_result_reddit["Sentiment"]}', '\n')
85
+
86
+ result = {
87
+ 'News_Article': sentiment_analysis_result_reddit["News_Article"],
88
+ 'Index':np.round(sentiment_analysis_result_reddit["Sentiment"][0]['score'],2)
89
+ }
90
+ analysis_results.append(np.append(result,np.append(article.split('URL:')[-1:], ((article.split('Date: ')[-1:])[0][0:10]))))
91
+ #pd.DataFrame(analysis_results).to_csv('analysis_results.csv')
92
+
93
+ #Generate summarized message rationalize dominant sentiment
94
+ summary = sentiment_analysis_util.generate_summary_of_sentiment(analysis_results) #, dominant_sentiment)
95
+ st.chat_message("assistant").write((summary))
96
+ st.session_state.messages.append({"role": "assistant", "content": summary})
97
+ #answers=np.append(res["messages"][-1].content,summary)
98
+
99
+ client = OpenAI(api_key=OPENAI_API_KEY)
100
+
101
+ if "openai_model" not in st.session_state:
102
+ st.session_state["openai_model"] = "gpt-3.5-turbo"
103
+
104
+ if prompt := st.chat_input("Any other questions? "):
105
+ # Add user message to chat history
106
+ st.session_state.messages.append({"role": "user", "content": prompt})
107
+ # Display user message in chat message container
108
+ with st.chat_message("user"):
109
+ st.markdown(prompt)
110
+ # Display assistant response in chat message container
111
+ with st.chat_message("assistant"):
112
+ stream = client.chat.completions.create(
113
+ model=st.session_state["openai_model"],
114
+ messages=[
115
+ {"role": m["role"], "content": m["content"]}
116
+ for m in st.session_state.messages
117
+ ],
118
+ stream=True,
119
+ )
120
+ response = st.write_stream(stream)
121
+ st.session_state.messages.append({"role": "assistant", "content": response})
122