-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
293 lines (244 loc) · 8.89 KB
/
app.py
File metadata and controls
293 lines (244 loc) · 8.89 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import streamlit as st
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from pycoingecko import CoinGeckoAPI
import random
# Initialize CoinGecko API with free endpoint
cg = CoinGeckoAPI()
# Download NLTK data safely
@st.cache_resource
def setup_nltk():
"""Setup NLTK resources."""
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt', quiet=True)
try:
nltk.data.find('corpora/stopwords')
except LookupError:
nltk.download('stopwords', quiet=True)
setup_nltk()
stop_words = set(stopwords.words('english'))
# Greeting and conversation patterns
greetings = {
'hello': ['Hello!', 'Hi there!', 'Hey!', 'Greetings!'],
'hi': ['Hi!', 'Hello!', 'Hey there!', 'Welcome!'],
'hey': ['Hey!', 'Hi!', 'Hello there!', 'Greetings!'],
'greetings': ['Greetings!', 'Hello!', 'Welcome!', 'Hi there!']
}
capabilities = """
I'm your Crypto Information Assistant, created by Ngenoh! 🚀
I can help you with:
1. Real-time Cryptocurrency Data:
- Current prices
- Market capitalization
- 24-hour price changes
- Latest market updates
2. Sustainability Information:
- Energy usage ratings
- Sustainability scores
- Environmental impact
3. Latest News:
- Recent developments
- Market updates
- Project news
4. Supported Cryptocurrencies:
- Bitcoin (BTC)
- Ethereum (ETH)
- Cardano (ADA)
Just ask me anything about these topics! For example:
- "What's Bitcoin's current price?"
- "Tell me about Ethereum's sustainability"
- "Show me Cardano's market cap and news"
Message sent by Ngenoh - Your Crypto Guide 🌟
"""
# Static sustainability and energy data (not available in API)
sustainability_data = {
"bitcoin": {
"energy_use": "high",
"sustainability_score": 3/10,
},
"ethereum": {
"energy_use": "medium",
"sustainability_score": 6/10,
},
"cardano": {
"energy_use": "low",
"sustainability_score": 8/10,
}
}
def is_greeting(text):
"""Check if the input is a greeting."""
text = text.lower().strip()
return (
text in greetings or
text.startswith('hi ') or
text.startswith('hello ') or
text.startswith('hey ')
)
def get_greeting_response():
"""Generate a random greeting response."""
all_greetings = []
for responses in greetings.values():
all_greetings.extend(responses)
return random.choice(all_greetings)
@st.cache_data(ttl=60) # Cache for 60 seconds
def get_crypto_data(crypto_id):
"""Get real-time data from CoinGecko API with caching."""
try:
data = cg.get_coin_by_id(
crypto_id,
localization=False,
tickers=False,
market_data=True,
community_data=False,
developer_data=False,
sparkline=False
)
market_data = data.get('market_data', {})
return {
'current_price': market_data.get('current_price', {}).get('usd'),
'market_cap': market_data.get('market_cap', {}).get('usd'),
'price_change_24h': market_data.get('price_change_percentage_24h'),
'last_updated': market_data.get('last_updated'),
}
except Exception as e:
st.error(f"Error fetching data: {str(e)}")
return None
def get_crypto_news(crypto_id):
"""Get latest news for a cryptocurrency."""
try:
news = cg.get_coin_by_id(
crypto_id,
localization=False,
tickers=False,
market_data=False,
community_data=False,
developer_data=False,
sparkline=False
)
return news.get('description', {}).get('en', '')[:200] + "..."
except Exception: # Removed unused 'e' variable
return "News data unavailable"
def preprocess_text(text):
"""Preprocess the input text for better understanding."""
# Tokenize and convert to lowercase
tokens = word_tokenize(text.lower())
# Remove punctuation and stopwords
tokens = [token for token in tokens if token.isalnum()]
tokens = [token for token in tokens if token not in stop_words]
return tokens
def analyze_crypto_query(user_question):
"""Analyze user question and provide response with real-time data."""
# Check for special commands
user_question = user_question.lower().strip()
# Handle greetings
if is_greeting(user_question):
greeting = get_greeting_response()
return f"{greeting}\n\n{capabilities}"
# Handle help request
if user_question in ['help', 'what can you do', 'capabilities']:
return capabilities
tokens = preprocess_text(user_question)
response = ""
# Define keyword mappings
keywords = {
'price': ['price', 'cost', 'worth', 'value'],
'market': ['market', 'cap', 'capitalization'],
'change': ['change', 'changed', 'movement', '24h', 'hours'],
'energy': ['energy', 'power', 'consumption'],
'green': ['sustainable', 'green', 'environment'],
'news': ['news', 'update', 'latest', 'happening']
}
# Map crypto names to CoinGecko IDs
crypto_mapping = {
'bitcoin': 'bitcoin',
'btc': 'bitcoin',
'ethereum': 'ethereum',
'eth': 'ethereum',
'cardano': 'cardano',
'ada': 'cardano'
}
# Identify mentioned cryptocurrencies
cryptos_to_show = []
for token in tokens:
if token in crypto_mapping:
cryptos_to_show.append(crypto_mapping[token])
if not cryptos_to_show:
cryptos_to_show = ['bitcoin', 'ethereum', 'cardano']
# Determine what information to show
show_price = any(word in tokens for word in keywords['price'])
show_market = any(word in tokens for word in keywords['market'])
show_change = any(word in tokens for word in keywords['change'])
show_energy = any(word in tokens for word in keywords['energy'])
show_green = any(word in tokens for word in keywords['green'])
show_news = any(word in tokens for word in keywords['news'])
show_all = not any([
show_price, show_market, show_change,
show_energy, show_green, show_news
])
# Generate response
for crypto_id in cryptos_to_show:
response += f"\n{crypto_id.title()}:\n"
# Get real-time data
market_data = get_crypto_data(crypto_id)
if market_data:
if show_all or show_price:
price = market_data['current_price']
response += f"Current Price: ${price:,.2f}\n"
if show_all or show_market:
cap = market_data['market_cap']
response += f"Market Cap: ${cap:,.0f}\n"
if show_all or show_change:
change = market_data['price_change_24h']
response += f"24h Change: {change:.1f}%\n"
if show_all or show_energy:
energy = sustainability_data[crypto_id]['energy_use']
response += f"Energy Usage: {energy}\n"
if show_all or show_green:
sustain = sustainability_data[crypto_id]['sustainability_score']
score = int(sustain * 100)
response += f"Sustainability Score: {score}/100\n"
if show_all or show_news:
news = get_crypto_news(crypto_id)
response += f"Latest News: {news}\n"
response += f"Last Updated: {market_data['last_updated']}\n"
else:
response += "Error fetching real-time data\n"
if not response.strip():
response = capabilities
# Add signature to all responses
response += "\n\nMessage sent by Ngenoh - Your Crypto Guide 🌟"
return response
# Streamlit UI
st.title("🤖 Crypto Information Bot by Ngenoh")
st.write("Ask me anything about Bitcoin, Ethereum, or Cardano!")
# Add a note about data sources
st.sidebar.markdown("""
## Data Sources
- Real-time market data: CoinGecko API
- Sustainability scores: Static database
- Energy usage: Static database
Created with ❤️ by Ngenoh
""")
# Initialize session state for chat history
if 'messages' not in st.session_state:
st.session_state.messages = []
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("What would you like to know?"):
# Display user message
st.chat_message("user").markdown(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("assistant"):
# Generate response
response = analyze_crypto_query(prompt)
# Display response
st.markdown(response)
st.session_state.messages.append(
{"role": "assistant", "content": response}
)