Spaces:
Sleeping
Sleeping
CryptoCreeper commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,26 +1,12 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
-
from huggingface_hub import InferenceClient
|
| 6 |
|
| 7 |
-
# -----------------------------------------------------------------------------
|
| 8 |
-
# 1. CONFIGURATION & STATE
|
| 9 |
-
# -----------------------------------------------------------------------------
|
| 10 |
-
# Global variable to store the latest market text for the AI
|
| 11 |
MARKET_CONTEXT = "Market data is loading..."
|
| 12 |
|
| 13 |
-
# Initialize the public model (no token required)
|
| 14 |
-
client = InferenceClient(model="Qwen/Qwen2.5-VL-3B-Instruct")
|
| 15 |
-
|
| 16 |
-
# -----------------------------------------------------------------------------
|
| 17 |
-
# 2. DATA FETCHING (CoinGecko)
|
| 18 |
-
# -----------------------------------------------------------------------------
|
| 19 |
def fetch_crypto_data():
|
| 20 |
-
"""
|
| 21 |
-
Fetches data from CoinGecko.
|
| 22 |
-
Returns: A list of dicts for the UI, and updates the global AI context.
|
| 23 |
-
"""
|
| 24 |
url = "https://api.coingecko.com/api/v3/coins/markets"
|
| 25 |
params = {
|
| 26 |
"vs_currency": "usd",
|
|
@@ -42,7 +28,6 @@ def fetch_crypto_data():
|
|
| 42 |
|
| 43 |
data = response.json()
|
| 44 |
|
| 45 |
-
# Build the context string for AI
|
| 46 |
context_parts = []
|
| 47 |
processed_data = []
|
| 48 |
|
|
@@ -54,7 +39,6 @@ def fetch_crypto_data():
|
|
| 54 |
mcap = coin['market_cap'] or 0
|
| 55 |
history = coin.get('sparkline_in_7d', {}).get('price', [])
|
| 56 |
|
| 57 |
-
# Add to AI context
|
| 58 |
context_parts.append(f"[{symbol}: ${price}, 24h:{chg_24:.1f}%, 7d:{chg_7d:.1f}%]")
|
| 59 |
|
| 60 |
processed_data.append({
|
|
@@ -74,12 +58,7 @@ def fetch_crypto_data():
|
|
| 74 |
print(f"API Error: {e}")
|
| 75 |
return None
|
| 76 |
|
| 77 |
-
# -----------------------------------------------------------------------------
|
| 78 |
-
# 3. UI HELPERS (Plots & HTML)
|
| 79 |
-
# -----------------------------------------------------------------------------
|
| 80 |
def create_sparkline(history, chg_24):
|
| 81 |
-
"""Creates a minimalist Plotly sparkline"""
|
| 82 |
-
# Green if positive, Red if negative
|
| 83 |
color = "#10B981" if chg_24 >= 0 else "#EF4444"
|
| 84 |
|
| 85 |
fig = go.Figure()
|
|
@@ -88,7 +67,7 @@ def create_sparkline(history, chg_24):
|
|
| 88 |
mode='lines',
|
| 89 |
fill='tozeroy',
|
| 90 |
line=dict(color=color, width=2),
|
| 91 |
-
fillcolor=f"rgba
|
| 92 |
))
|
| 93 |
|
| 94 |
fig.update_layout(
|
|
@@ -104,7 +83,6 @@ def create_sparkline(history, chg_24):
|
|
| 104 |
return fig
|
| 105 |
|
| 106 |
def create_card_html(coin):
|
| 107 |
-
"""Generates the HTML card for a single coin"""
|
| 108 |
if not coin:
|
| 109 |
return "<div style='color:white;'>Error Loading</div>"
|
| 110 |
|
|
@@ -133,12 +111,10 @@ def create_card_html(coin):
|
|
| 133 |
return html
|
| 134 |
|
| 135 |
def refresh_dashboard():
|
| 136 |
-
"""Main function called to update the dashboard"""
|
| 137 |
data = fetch_crypto_data()
|
| 138 |
|
| 139 |
-
# If API fails (rate limit), return dummy updates
|
| 140 |
if not data:
|
| 141 |
-
return [gr.update()] * 8
|
| 142 |
|
| 143 |
outputs = []
|
| 144 |
for coin in data:
|
|
@@ -147,42 +123,37 @@ def refresh_dashboard():
|
|
| 147 |
|
| 148 |
return outputs
|
| 149 |
|
| 150 |
-
# -----------------------------------------------------------------------------
|
| 151 |
-
# 4. AI CHAT LOGIC
|
| 152 |
-
# -----------------------------------------------------------------------------
|
| 153 |
def chat_logic(message, history):
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
LIVE MARKET DATA (Use this if asked about prices):
|
| 157 |
-
{MARKET_CONTEXT}
|
| 158 |
-
|
| 159 |
-
INSTRUCTIONS:
|
| 160 |
-
1. If the user asks for the price, trend, or stats of a coin, USE THE LIVE DATA above.
|
| 161 |
-
2. If the user asks general questions ("What is mining?", "Who is Satoshi?"), answer normally.
|
| 162 |
-
3. Keep answers concise, helpful, and professional.
|
| 163 |
-
"""
|
| 164 |
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
|
|
|
| 167 |
for human, assistant in history:
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
try:
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
if
|
| 178 |
-
|
| 179 |
-
|
| 180 |
except Exception as e:
|
| 181 |
-
yield f"⚠️
|
| 182 |
|
| 183 |
-
# -----------------------------------------------------------------------------
|
| 184 |
-
# 5. GRADIO APP LAYOUT
|
| 185 |
-
# -----------------------------------------------------------------------------
|
| 186 |
custom_css = """
|
| 187 |
body { background-color: #111827; }
|
| 188 |
.contain { max-width: 1400px; margin: auto; padding-top: 20px; }
|
|
@@ -191,55 +162,40 @@ h1 { color: #F3F4F6; text-align: center; margin-bottom: 30px; }
|
|
| 191 |
footer { visibility: hidden; }
|
| 192 |
"""
|
| 193 |
|
| 194 |
-
# We define the theme on the Blocks object, but remove it from ChatInterface
|
| 195 |
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate")) as demo:
|
| 196 |
|
| 197 |
gr.HTML("<h1>⚡ CryptoDash AI</h1>")
|
| 198 |
|
| 199 |
-
# --- DASHBOARD ROW ---
|
| 200 |
-
# We initialize with empty plots/html, they get filled by the load() event
|
| 201 |
with gr.Row():
|
| 202 |
-
# Column 1: BTC
|
| 203 |
with gr.Column():
|
| 204 |
c1_html = gr.HTML()
|
| 205 |
c1_plot = gr.Plot(show_label=False, container=False)
|
| 206 |
-
|
| 207 |
-
# Column 2: ETH
|
| 208 |
with gr.Column():
|
| 209 |
c2_html = gr.HTML()
|
| 210 |
c2_plot = gr.Plot(show_label=False, container=False)
|
| 211 |
-
|
| 212 |
-
# Column 3: SOL
|
| 213 |
with gr.Column():
|
| 214 |
c3_html = gr.HTML()
|
| 215 |
c3_plot = gr.Plot(show_label=False, container=False)
|
| 216 |
-
|
| 217 |
-
# Column 4: BNB
|
| 218 |
with gr.Column():
|
| 219 |
c4_html = gr.HTML()
|
| 220 |
c4_plot = gr.Plot(show_label=False, container=False)
|
| 221 |
|
| 222 |
btn_refresh = gr.Button("🔄 Refresh Market Data", variant="secondary")
|
| 223 |
|
| 224 |
-
# --- CHAT SECTION ---
|
| 225 |
gr.HTML("<br><div style='height: 1px; background-color: #374151; margin: 20px 0;'></div>")
|
| 226 |
gr.Markdown("### 🤖 Qwen Crypto Assistant")
|
| 227 |
|
| 228 |
-
# NOTE: Removed 'theme' argument here to fix the error
|
| 229 |
chat = gr.ChatInterface(
|
| 230 |
fn=chat_logic,
|
| 231 |
examples=["What is the price of Bitcoin?", "Is the market up today?", "Explain market cap"],
|
| 232 |
)
|
| 233 |
|
| 234 |
-
# --- EVENT WIRING ---
|
| 235 |
-
# Load data immediately when app starts
|
| 236 |
demo.load(
|
| 237 |
fn=refresh_dashboard,
|
| 238 |
inputs=None,
|
| 239 |
outputs=[c1_html, c1_plot, c2_html, c2_plot, c3_html, c3_plot, c4_html, c4_plot]
|
| 240 |
)
|
| 241 |
|
| 242 |
-
# Refresh button click
|
| 243 |
btn_refresh.click(
|
| 244 |
fn=refresh_dashboard,
|
| 245 |
inputs=None,
|
|
@@ -247,4 +203,4 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="indigo", neutra
|
|
| 247 |
)
|
| 248 |
|
| 249 |
if __name__ == "__main__":
|
| 250 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
+
import json
|
| 4 |
import pandas as pd
|
| 5 |
import plotly.graph_objects as go
|
|
|
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
MARKET_CONTEXT = "Market data is loading..."
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
def fetch_crypto_data():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
url = "https://api.coingecko.com/api/v3/coins/markets"
|
| 11 |
params = {
|
| 12 |
"vs_currency": "usd",
|
|
|
|
| 28 |
|
| 29 |
data = response.json()
|
| 30 |
|
|
|
|
| 31 |
context_parts = []
|
| 32 |
processed_data = []
|
| 33 |
|
|
|
|
| 39 |
mcap = coin['market_cap'] or 0
|
| 40 |
history = coin.get('sparkline_in_7d', {}).get('price', [])
|
| 41 |
|
|
|
|
| 42 |
context_parts.append(f"[{symbol}: ${price}, 24h:{chg_24:.1f}%, 7d:{chg_7d:.1f}%]")
|
| 43 |
|
| 44 |
processed_data.append({
|
|
|
|
| 58 |
print(f"API Error: {e}")
|
| 59 |
return None
|
| 60 |
|
|
|
|
|
|
|
|
|
|
| 61 |
def create_sparkline(history, chg_24):
|
|
|
|
|
|
|
| 62 |
color = "#10B981" if chg_24 >= 0 else "#EF4444"
|
| 63 |
|
| 64 |
fig = go.Figure()
|
|
|
|
| 67 |
mode='lines',
|
| 68 |
fill='tozeroy',
|
| 69 |
line=dict(color=color, width=2),
|
| 70 |
+
fillcolor=f"rgba({int(color[1:3], 16)}, {int(color[3:5], 16)}, {int(color[5:7], 16)}, 0.1)"
|
| 71 |
))
|
| 72 |
|
| 73 |
fig.update_layout(
|
|
|
|
| 83 |
return fig
|
| 84 |
|
| 85 |
def create_card_html(coin):
|
|
|
|
| 86 |
if not coin:
|
| 87 |
return "<div style='color:white;'>Error Loading</div>"
|
| 88 |
|
|
|
|
| 111 |
return html
|
| 112 |
|
| 113 |
def refresh_dashboard():
|
|
|
|
| 114 |
data = fetch_crypto_data()
|
| 115 |
|
|
|
|
| 116 |
if not data:
|
| 117 |
+
return [gr.update()] * 8
|
| 118 |
|
| 119 |
outputs = []
|
| 120 |
for coin in data:
|
|
|
|
| 123 |
|
| 124 |
return outputs
|
| 125 |
|
|
|
|
|
|
|
|
|
|
| 126 |
def chat_logic(message, history):
|
| 127 |
+
API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-VL-3B-Instruct"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
system_prompt = f"""You are a professional Crypto Dashboard Assistant.
|
| 130 |
+
LIVE MARKET DATA: {MARKET_CONTEXT}
|
| 131 |
+
1. Use live data for prices/stats.
|
| 132 |
+
2. Answer general questions normally.
|
| 133 |
+
3. Be concise and professional."""
|
| 134 |
|
| 135 |
+
payload_messages = [{"role": "system", "content": system_prompt}]
|
| 136 |
for human, assistant in history:
|
| 137 |
+
payload_messages.append({"role": "user", "content": human})
|
| 138 |
+
payload_messages.append({"role": "assistant", "content": assistant})
|
| 139 |
+
payload_messages.append({"role": "user", "content": message})
|
| 140 |
+
|
| 141 |
+
payload = {
|
| 142 |
+
"model": "Qwen/Qwen2.5-VL-3B-Instruct",
|
| 143 |
+
"messages": payload_messages,
|
| 144 |
+
"parameters": {"max_new_tokens": 512, "temperature": 0.7}
|
| 145 |
+
}
|
| 146 |
|
| 147 |
try:
|
| 148 |
+
response = requests.post(API_URL, json=payload, timeout=20)
|
| 149 |
+
if response.status_code == 200:
|
| 150 |
+
result = response.json()
|
| 151 |
+
yield result[0]['generated_text'] if isinstance(result, list) else result['choices'][0]['message']['content']
|
| 152 |
+
else:
|
| 153 |
+
yield f"⚠️ API Error: {response.status_code} - {response.text}"
|
| 154 |
except Exception as e:
|
| 155 |
+
yield f"⚠️ Connection Error: {str(e)}"
|
| 156 |
|
|
|
|
|
|
|
|
|
|
| 157 |
custom_css = """
|
| 158 |
body { background-color: #111827; }
|
| 159 |
.contain { max-width: 1400px; margin: auto; padding-top: 20px; }
|
|
|
|
| 162 |
footer { visibility: hidden; }
|
| 163 |
"""
|
| 164 |
|
|
|
|
| 165 |
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate")) as demo:
|
| 166 |
|
| 167 |
gr.HTML("<h1>⚡ CryptoDash AI</h1>")
|
| 168 |
|
|
|
|
|
|
|
| 169 |
with gr.Row():
|
|
|
|
| 170 |
with gr.Column():
|
| 171 |
c1_html = gr.HTML()
|
| 172 |
c1_plot = gr.Plot(show_label=False, container=False)
|
|
|
|
|
|
|
| 173 |
with gr.Column():
|
| 174 |
c2_html = gr.HTML()
|
| 175 |
c2_plot = gr.Plot(show_label=False, container=False)
|
|
|
|
|
|
|
| 176 |
with gr.Column():
|
| 177 |
c3_html = gr.HTML()
|
| 178 |
c3_plot = gr.Plot(show_label=False, container=False)
|
|
|
|
|
|
|
| 179 |
with gr.Column():
|
| 180 |
c4_html = gr.HTML()
|
| 181 |
c4_plot = gr.Plot(show_label=False, container=False)
|
| 182 |
|
| 183 |
btn_refresh = gr.Button("🔄 Refresh Market Data", variant="secondary")
|
| 184 |
|
|
|
|
| 185 |
gr.HTML("<br><div style='height: 1px; background-color: #374151; margin: 20px 0;'></div>")
|
| 186 |
gr.Markdown("### 🤖 Qwen Crypto Assistant")
|
| 187 |
|
|
|
|
| 188 |
chat = gr.ChatInterface(
|
| 189 |
fn=chat_logic,
|
| 190 |
examples=["What is the price of Bitcoin?", "Is the market up today?", "Explain market cap"],
|
| 191 |
)
|
| 192 |
|
|
|
|
|
|
|
| 193 |
demo.load(
|
| 194 |
fn=refresh_dashboard,
|
| 195 |
inputs=None,
|
| 196 |
outputs=[c1_html, c1_plot, c2_html, c2_plot, c3_html, c3_plot, c4_html, c4_plot]
|
| 197 |
)
|
| 198 |
|
|
|
|
| 199 |
btn_refresh.click(
|
| 200 |
fn=refresh_dashboard,
|
| 201 |
inputs=None,
|
|
|
|
| 203 |
)
|
| 204 |
|
| 205 |
if __name__ == "__main__":
|
| 206 |
+
demo.launch()
|