CryptoCreeper commited on
Commit
07cb30f
·
verified ·
1 Parent(s): 42e28c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -73
app.py CHANGED
@@ -1,10 +1,19 @@
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"
@@ -15,7 +24,7 @@ def fetch_crypto_data():
15
  "per_page": 4,
16
  "page": 1,
17
  "sparkline": "true",
18
- "price_change_percentage": "24h,7d"
19
  }
20
 
21
  global MARKET_CONTEXT
@@ -32,15 +41,14 @@ def fetch_crypto_data():
32
  for coin in data:
33
  symbol = coin['symbol'].upper()
34
  price = coin['current_price']
35
- chg_24 = coin.get('price_change_percentage_24h_in_currency', 0) or 0
36
- chg_7d = coin.get('price_change_percentage_7d_in_currency', 0) or 0
37
  mcap = coin['market_cap'] or 0
38
  history = coin.get('sparkline_in_7d', {}).get('price', [])
39
 
40
- context_parts.append(f"[{symbol}: ${price}, 24h:{chg_24:.1f}%, 7d:{chg_7d:.1f}%]")
41
  processed_data.append({
42
  "name": coin['name'], "symbol": symbol, "price": price,
43
- "chg_24": chg_24, "chg_7d": chg_7d, "mcap": mcap, "history": history
44
  })
45
 
46
  MARKET_CONTEXT = " | ".join(context_parts)
@@ -48,38 +56,63 @@ def fetch_crypto_data():
48
  except Exception:
49
  return None
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def create_sparkline(history, chg_24):
52
  color = "#10B981" if chg_24 >= 0 else "#EF4444"
53
  fig = go.Figure()
54
- fig.add_trace(go.Scatter(
55
- y=history, mode='lines', fill='tozeroy',
56
- line=dict(color=color, width=2),
57
- fillcolor=f"rgba({int(color[1:3], 16)}, {int(color[3:5], 16)}, {int(color[5:7], 16)}, 0.1)"
58
- ))
59
  fig.update_layout(
60
  template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
61
- margin=dict(l=0, r=0, t=10, b=0), xaxis=dict(visible=False), yaxis=dict(visible=False),
62
- showlegend=False, height=80,
63
  )
64
  return fig
65
 
66
  def create_card_html(coin):
67
- if not coin: return "<div style='color:white;'>Error Loading</div>"
68
  color_24 = "#10B981" if coin['chg_24'] >= 0 else "#EF4444"
69
- arrow = "▲" if coin['chg_24'] >= 0 else "▼"
70
  return f"""
71
- <div style="background-color: #1F2937; padding: 20px; border-radius: 12px; border: 1px solid #374151;">
72
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
73
- <div style="display: flex; align-items: baseline; gap: 8px;">
74
- <h2 style="margin: 0; font-size: 1.25rem; color: #F3F4F6;">{coin['name']}</h2>
75
- <span style="color: #9CA3AF;">{coin['symbol']}</span>
76
- </div>
77
- <span style="font-size: 1.25rem; color: #F3F4F6;">${coin['price']:,.2f}</span>
78
- </div>
79
- <div style="display: flex; justify-content: space-between; font-size: 0.875rem;">
80
- <div style="color: {color_24}; font-weight: 600;">{arrow} {coin['chg_24']:.2f}%</div>
81
- <div style="color: #9CA3AF;">MCap: ${coin['mcap']/1e9:.1f}B</div>
82
  </div>
 
83
  </div>
84
  """
85
 
@@ -92,59 +125,25 @@ def refresh_dashboard():
92
  outputs.append(create_sparkline(coin['history'], coin['chg_24']))
93
  return outputs
94
 
95
- def chat_logic(message, history):
96
- API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-7B-Instruct"
97
-
98
- system_prompt = f"You are a professional Crypto Dashboard Assistant. LIVE MARKET DATA: {MARKET_CONTEXT}"
99
- payload_messages = [{"role": "system", "content": system_prompt}]
100
- for human, assistant in history:
101
- payload_messages.append({"role": "user", "content": human})
102
- payload_messages.append({"role": "assistant", "content": assistant})
103
- payload_messages.append({"role": "user", "content": message})
104
 
105
- payload = {
106
- "inputs": message, # Simple input format for public API requests
107
- "parameters": {"max_new_tokens": 512, "temperature": 0.7},
108
- }
109
-
110
- try:
111
- # Standard request without Authorization header
112
- response = requests.post(API_URL, json=payload, timeout=20)
113
- if response.status_code == 200:
114
- result = response.json()
115
- # Handle different return formats from HF API
116
- if isinstance(result, list) and "generated_text" in result[0]:
117
- yield result[0]["generated_text"]
118
- elif isinstance(result, dict) and "generated_text" in result:
119
- yield result["generated_text"]
120
- else:
121
- yield str(result)
122
- elif response.status_code == 429:
123
- yield "⚠️ Rate limit reached (Public requests are limited). Try again in a moment."
124
- else:
125
- yield f"⚠️ API Error: {response.status_code}"
126
- except Exception as e:
127
- yield f"⚠️ Connection Error: {str(e)}"
128
-
129
- custom_css = "body { background-color: #111827; } .contain { max-width: 1400px; margin: auto; padding-top: 20px; }"
130
-
131
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate")) as demo:
132
- gr.HTML("<h1 style='color: white; text-align: center;'>⚡ CryptoDash AI (Qwen 7B)</h1>")
133
  with gr.Row():
134
  with gr.Column():
135
- c1_html, c1_plot = gr.HTML(), gr.Plot(show_label=False, container=False)
136
  with gr.Column():
137
- c2_html, c2_plot = gr.HTML(), gr.Plot(show_label=False, container=False)
138
  with gr.Column():
139
- c3_html, c3_plot = gr.HTML(), gr.Plot(show_label=False, container=False)
140
  with gr.Column():
141
- c4_html, c4_plot = gr.HTML(), gr.Plot(show_label=False, container=False)
142
 
143
- btn_refresh = gr.Button("🔄 Refresh Market Data", variant="secondary")
144
- gr.ChatInterface(fn=chat_logic, examples=["What is the price of Bitcoin?"])
 
145
 
146
- demo.load(fn=refresh_dashboard, outputs=[c1_html, c1_plot, c2_html, c2_plot, c3_html, c3_plot, c4_html, c4_plot])
147
- btn_refresh.click(fn=refresh_dashboard, outputs=[c1_html, c1_plot, c2_html, c2_plot, c3_html, c3_plot, c4_html, c4_plot])
148
 
149
  if __name__ == "__main__":
150
  demo.launch()
 
1
  import gradio as gr
2
  import requests
3
+ import torch
4
+ import re
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
6
 
7
  MARKET_CONTEXT = "Market data is loading..."
8
+ MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
9
+
10
+ device = "cuda" if torch.cuda.is_available() else "cpu"
11
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
12
+ model = AutoModelForCausalLM.from_pretrained(
13
+ MODEL_ID,
14
+ torch_dtype="auto",
15
+ device_map="auto"
16
+ )
17
 
18
  def fetch_crypto_data():
19
  url = "https://api.coingecko.com/api/v3/coins/markets"
 
24
  "per_page": 4,
25
  "page": 1,
26
  "sparkline": "true",
27
+ "price_change_percentage": "24h"
28
  }
29
 
30
  global MARKET_CONTEXT
 
41
  for coin in data:
42
  symbol = coin['symbol'].upper()
43
  price = coin['current_price']
44
+ chg_24 = coin.get('price_change_percentage_24h', 0) or 0
 
45
  mcap = coin['market_cap'] or 0
46
  history = coin.get('sparkline_in_7d', {}).get('price', [])
47
 
48
+ context_parts.append(f"[{symbol}: ${price}, 24h:{chg_24:.1f}%]")
49
  processed_data.append({
50
  "name": coin['name'], "symbol": symbol, "price": price,
51
+ "chg_24": chg_24, "mcap": mcap, "history": history
52
  })
53
 
54
  MARKET_CONTEXT = " | ".join(context_parts)
 
56
  except Exception:
57
  return None
58
 
59
+ def chat_logic(user_input, history):
60
+ fetch_crypto_data()
61
+
62
+ system_prompt = f"You are a professional Crypto Assistant. LIVE DATA: {MARKET_CONTEXT}. Answer concisely."
63
+
64
+ messages = [{"role": "system", "content": system_prompt}]
65
+ for human, assistant in history:
66
+ messages.append({"role": "user", "content": human})
67
+ messages.append({"role": "assistant", "content": assistant})
68
+ messages.append({"role": "user", "content": user_input})
69
+
70
+ text = tokenizer.apply_chat_template(
71
+ messages,
72
+ tokenize=False,
73
+ add_generation_prompt=True
74
+ )
75
+
76
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
77
+
78
+ generated_ids = model.generate(
79
+ **model_inputs,
80
+ max_new_tokens=512,
81
+ do_sample=True,
82
+ temperature=0.7
83
+ )
84
+
85
+ response_ids = [
86
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
87
+ ]
88
+
89
+ response = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0]
90
+
91
+ cleaned_response = re.sub(r'<think>.*?</think>\s*\n?', '', response, flags=re.DOTALL).strip()
92
+ return cleaned_response
93
+
94
+ import plotly.graph_objects as go
95
+
96
  def create_sparkline(history, chg_24):
97
  color = "#10B981" if chg_24 >= 0 else "#EF4444"
98
  fig = go.Figure()
99
+ fig.add_trace(go.Scatter(y=history, mode='lines', fill='tozeroy', line=dict(color=color, width=2)))
 
 
 
 
100
  fig.update_layout(
101
  template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
102
+ margin=dict(l=0, r=0, t=0, b=0), xaxis=dict(visible=False), yaxis=dict(visible=False),
103
+ showlegend=False, height=60
104
  )
105
  return fig
106
 
107
  def create_card_html(coin):
 
108
  color_24 = "#10B981" if coin['chg_24'] >= 0 else "#EF4444"
 
109
  return f"""
110
+ <div style="background-color: #1F2937; padding: 15px; border-radius: 10px; border: 1px solid #374151; color: white;">
111
+ <div style="display: flex; justify-content: space-between;">
112
+ <b>{coin['name']} ({coin['symbol']})</b>
113
+ <span>${coin['price']:,.2f}</span>
 
 
 
 
 
 
 
114
  </div>
115
+ <div style="color: {color_24}; font-size: 0.8em;">{coin['chg_24']:.2f}% (24h)</div>
116
  </div>
117
  """
118
 
 
125
  outputs.append(create_sparkline(coin['history'], coin['chg_24']))
126
  return outputs
127
 
128
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
129
+ gr.HTML("<h1 style='text-align: center;'>⚡ Local Qwen CryptoDash</h1>")
 
 
 
 
 
 
 
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  with gr.Row():
132
  with gr.Column():
133
+ c1_h = gr.HTML(); c1_p = gr.Plot(container=False)
134
  with gr.Column():
135
+ c2_h = gr.HTML(); c2_p = gr.Plot(container=False)
136
  with gr.Column():
137
+ c3_h = gr.HTML(); c3_p = gr.Plot(container=False)
138
  with gr.Column():
139
+ c4_h = gr.HTML(); c4_p = gr.Plot(container=False)
140
 
141
+ btn = gr.Button("Update Market")
142
+
143
+ gr.ChatInterface(fn=chat_logic)
144
 
145
+ demo.load(refresh_dashboard, outputs=[c1_h, c1_p, c2_h, c2_p, c3_h, c3_p, c4_h, c4_p])
146
+ btn.click(refresh_dashboard, outputs=[c1_h, c1_p, c2_h, c2_p, c3_h, c3_p, c4_h, c4_p])
147
 
148
  if __name__ == "__main__":
149
  demo.launch()