Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
3 |
+
import requests
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
|
7 |
+
# --- API Key ---
|
8 |
+
CMC_API_KEY = os.environ.get("CMC_API_KEY") # Store your API key as a Hugging Face Secret
|
9 |
+
|
10 |
+
if not CMC_API_KEY:
|
11 |
+
st.warning("Please add your CoinMarketCap API key as a Secret in Hugging Face Spaces.")
|
12 |
+
else:
|
13 |
+
headers = {
|
14 |
+
'X-CMC_PRO_API_KEY': CMC_API_KEY,
|
15 |
+
'Accepts': 'application/json'
|
16 |
+
}
|
17 |
+
|
18 |
+
# --- Data Fetching ---
|
19 |
+
@st.cache_data(ttl=60) # Cache data for 60 seconds
|
20 |
+
def get_crypto_price(symbol):
|
21 |
+
url = f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol={symbol}'
|
22 |
+
try:
|
23 |
+
response = requests.get(url, headers=headers)
|
24 |
+
response.raise_for_status()
|
25 |
+
data = json.loads(response.text)
|
26 |
+
if data['status']['error_code'] == 0:
|
27 |
+
price = data['data'][symbol]['quote']['USD']['price']
|
28 |
+
return price
|
29 |
+
else:
|
30 |
+
return f"Error fetching data: {data['status']['error_message']}"
|
31 |
+
except requests.exceptions.RequestException as e:
|
32 |
+
return f"Error connecting to CoinMarketCap API: {e}"
|
33 |
+
|
34 |
+
# --- AI Model Integration ---
|
35 |
+
@st.cache_resource
|
36 |
+
def load_sentiment_model():
|
37 |
+
tokenizer = AutoTokenizer.from_pretrained("ElKulako/cryptobert")
|
38 |
+
model = AutoModelForSequenceClassification.from_pretrained("ElKulako/cryptobert")
|
39 |
+
return tokenizer, model
|
40 |
+
|
41 |
+
@st.cache_data
|
42 |
+
def analyze_sentiment(text, tokenizer, model):
|
43 |
+
try:
|
44 |
+
inputs = tokenizer(text, return_tensors="pt")
|
45 |
+
outputs = model(**inputs)
|
46 |
+
logits = outputs.logits
|
47 |
+
predicted_class_id = logits.argmax().item()
|
48 |
+
return model.config.id2label[predicted_class_id]
|
49 |
+
except Exception as e:
|
50 |
+
return f"Error analyzing sentiment: {e}"
|
51 |
+
|
52 |
+
tokenizer, sentiment_model = load_sentiment_model()
|
53 |
+
|
54 |
+
# --- Main Chatbot Logic ---
|
55 |
+
def process_user_message(user_input):
|
56 |
+
user_input_lower = user_input.lower()
|
57 |
+
|
58 |
+
if "current price of" in user_input_lower:
|
59 |
+
symbol = user_input_lower.split("current price of")[1].strip().upper()
|
60 |
+
price = get_crypto_price(symbol)
|
61 |
+
if isinstance(price, str) and "Error" in price:
|
62 |
+
return price
|
63 |
+
else:
|
64 |
+
sentiment_summary = analyze_sentiment(f"Recent news about {symbol}", tokenizer, sentiment_model)
|
65 |
+
return f"The current price of {symbol} is ${price:.2f}. Market sentiment is currently {sentiment_summary}."
|
66 |
+
elif "should i buy" in user_input_lower:
|
67 |
+
return "I am currently unable to provide buy/sell recommendations without technical analysis capabilities in this deployment."
|
68 |
+
elif "rsi say about" in user_input_lower:
|
69 |
+
return "I am currently unable to analyze RSI without the necessary libraries in this deployment."
|
70 |
+
else:
|
71 |
+
return "I'm still learning! I can currently tell you the price of a cryptocurrency and analyze the sentiment of related news."
|
72 |
+
|
73 |
+
# --- Streamlit UI ---
|
74 |
+
st.title("Crypto Trading Assistant")
|
75 |
+
st.markdown("Ask me about cryptocurrency prices and market sentiment.")
|
76 |
+
|
77 |
+
user_query = st.text_input("Your question:", "")
|
78 |
+
|
79 |
+
if CMC_API_KEY:
|
80 |
+
if user_query:
|
81 |
+
with st.spinner("Thinking..."):
|
82 |
+
bot_response = process_user_message(user_query)
|
83 |
+
st.write(f"**Bot:** {bot_response}")
|
84 |
+
|
85 |
+
# Simple price chart example if the user asked for the price
|
86 |
+
if "price of" in user_query.lower():
|
87 |
+
symbol = user_query.lower().split("price of")[1].strip().upper()
|
88 |
+
price_data = get_crypto_price(symbol)
|
89 |
+
if not isinstance(price_data, str):
|
90 |
+
st.subheader(f"Current Price of {symbol}: ${price_data:.2f}")
|
91 |
+
st.line_chart([price_data]) # Simple single point chart
|
92 |
+
else:
|
93 |
+
st.error("CoinMarketCap API key is missing. Please add it as a Secret.")
|