KatGaw commited on
Commit
ba6b805
β€’
1 Parent(s): d07ec1d
Files changed (1) hide show
  1. app.py +112 -25
app.py CHANGED
@@ -5,36 +5,123 @@ 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 "chat_history" 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 cryptocurrency investment reccommendations. Say I don't know if you don't know.
23
+ """}]
24
+
25
+ if 'count' not in st.session_state:
26
+ st.session_state['count'] = 0
27
+
28
+ # If not, then initialize it
29
+ if 'key' not in st.session_state:
30
+ st.session_state['key'] = 'value'
31
+
32
+ # Session State also supports the attribute based syntax
33
+ if 'key' not in st.session_state:
34
+ st.session_state.key = 'value'
35
+
36
+ #st.image('el_pic.png')
37
+
38
+ sideb=st.sidebar
39
+ with st.sidebar:
40
+ prompt=st.text_input("Enter topic for sentiment analysis: ")
41
+
42
+ check1=sideb.button(f"analyze {prompt}")
43
+
44
+ if check1:
45
+ # Add user message to chat history
46
  st.session_state.messages.append({"role": "user", "content": prompt})
47
+ # Display user message in chat message container
48
+ with st.chat_message("user"):
49
+ st.markdown(prompt)
50
+
51
+ # ========================== Sentiment analysis
52
+ #Perform sentiment analysis on the cryptocurrency news & predict dominant sentiment along with plotting the sentiment breakdown chart
53
+ # Downloading from reddit
54
+
55
+ # Downloading from alpaca
56
+ if len(prompt.split(' '))<2:
57
+ print('here')
58
+ st.write('I am analyzing Google News ...')
59
+ news_articles = sentiment_analysis_util.fetch_news(str(prompt))
60
+ st.write('Now, I am analyzing Reddit ...')
61
+ reddit_news_articles=sentiment_analysis_util.fetch_reddit_news(prompt)
62
+ analysis_results = []
63
+
64
+ #Perform sentiment analysis for each product review
65
+ if len(prompt.split(' '))<2:
66
+ print('here')
67
+ for article in news_articles:
68
+ if prompt.lower()[0:6] in article['News_Article'].lower():
69
+ sentiment_analysis_result = sentiment_analysis_util.analyze_sentiment(article['News_Article'])
70
 
71
+ # Display sentiment analysis results
72
+ #print(f'News Article: {sentiment_analysis_result["News_Article"]} : Sentiment: {sentiment_analysis_result["Sentiment"]}', '\n')
73
+
74
+ result = {
75
+ 'News_Article': sentiment_analysis_result["News_Article"],
76
+ 'Sentiment': sentiment_analysis_result["Sentiment"][0]['label'],
77
+ 'Index': sentiment_analysis_result["Sentiment"][0]['score'],
78
+ 'URL': article['URL']
79
+ }
80
+
81
+ analysis_results.append(result)
82
+
83
+ articles_url=[]
84
+ for article in reddit_news_articles:
85
+ if prompt.lower()[0:6] in article.lower():
86
+ sentiment_analysis_result_reddit = sentiment_analysis_util.analyze_sentiment(article)
87
+
88
+ # Display sentiment analysis results
89
+ #print(f'News Article: {sentiment_analysis_result_reddit["News_Article"]} : Sentiment: {sentiment_analysis_result_reddit["Sentiment"]}', '\n')
90
+
91
+ result = {
92
+ 'News_Article': sentiment_analysis_result_reddit["News_Article"],
93
+ 'Index':np.round(sentiment_analysis_result_reddit["Sentiment"][0]['score'],2)
94
+ }
95
+ analysis_results.append(np.append(result,np.append(article.split('URL:')[-1:], ((article.split('Date: ')[-1:])[0][0:10]))))
96
+ #pd.DataFrame(analysis_results).to_csv('analysis_results.csv')
97
+
98
+ #Generate summarized message rationalize dominant sentiment
99
+ summary = sentiment_analysis_util.generate_summary_of_sentiment(analysis_results) #, dominant_sentiment)
100
+ st.chat_message("assistant").write((summary))
101
+ st.session_state.messages.append({"role": "assistant", "content": summary})
102
+ #answers=np.append(res["messages"][-1].content,summary)
103
+
104
+ client = OpenAI(api_key=OPENAI_API_KEY)
105
+
106
+ if "openai_model" not in st.session_state:
107
+ st.session_state["openai_model"] = "gpt-3.5-turbo"
108
+
109
+ if prompt := st.chat_input("Any other questions? "):
110
+ # Add user message to chat history
111
+ st.session_state.messages.append({"role": "user", "content": prompt})
112
+ # Display user message in chat message container
113
+ with st.chat_message("user"):
114
+ st.markdown(prompt)
115
+ # Display assistant response in chat message container
116
+ with st.chat_message("assistant"):
117
+ stream = client.chat.completions.create(
118
+ model=st.session_state["openai_model"],
119
+ messages=[
120
+ {"role": m["role"], "content": m["content"]}
121
+ for m in st.session_state.messages
122
+ ],
123
+ stream=True,
124
+ )
125
+ response = st.write_stream(stream)
126
+ st.session_state.messages.append({"role": "assistant", "content": response})
127