sithuWiki commited on
Commit
32e930f
ยท
verified ยท
1 Parent(s): c8514df

upload app.py

Browse files
Files changed (1) hide show
  1. app.py +305 -0
app.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MineROI-Net Gradio App - Updated to use complete historical blockchain data"""
2
+
3
+ import gradio as gr
4
+ import pandas as pd
5
+ import plotly.graph_objects as go
6
+ from datetime import datetime, timedelta
7
+ import os
8
+ from miner_specs import MINER_SPECS, get_miner_list, ELECTRICITY_RATES
9
+ from fetch_blockchain_data import get_blockchain_data_for_date, load_complete_blockchain_data
10
+ from preprocessing import get_latest_sequence
11
+ from electricity_prices import get_electricity_rate
12
+ from predictor import MineROIPredictor
13
+ from fetch_asic_prices import fetch_asic_price_for_date, FALLBACK_PRICES
14
+
15
+ MODEL_PATH = "best_model_weights.pth"
16
+
17
+ # Predictor (global)
18
+ predictor = None
19
+
20
+
21
+ def init_predictor():
22
+ """Initialize predictor once"""
23
+ global predictor
24
+ if predictor is None:
25
+ predictor = MineROIPredictor(MODEL_PATH)
26
+
27
+
28
+ def init_app():
29
+ """Initialize app - load complete blockchain data into memory"""
30
+ print("\n" + "="*80)
31
+ print("๐Ÿš€ INITIALIZING MINEROI-NET APP")
32
+ print("="*80)
33
+
34
+ # Load complete blockchain data into memory (one-time)
35
+ complete_df = load_complete_blockchain_data()
36
+
37
+ if complete_df is not None:
38
+ print(f"\nโœ… Complete blockchain data loaded successfully!")
39
+ print(f" {len(complete_df):,} days available")
40
+ print(f" Date range: {complete_df['date'].min().date()} to {complete_df['date'].max().date()}")
41
+ print(f"\nโœ… You can now predict for ANY date in this range!")
42
+ else:
43
+ print(f"\nโš ๏ธ WARNING: blockchain_data_complete.csv not found!")
44
+ print(f" App will work with limited recent data only")
45
+ print(f"\n๐Ÿ“ฅ To enable full historical predictions:")
46
+ print(f" 1. Run: python download_complete_blockchain_data.py")
47
+ print(f" 2. Upload blockchain_data_complete.csv to your Gradio space")
48
+
49
+ print("="*80 + "\n")
50
+
51
+ # Initialize predictor
52
+ init_predictor()
53
+
54
+
55
+ def predict_roi(miner_name, region, prediction_date):
56
+ """Make prediction for a specific date"""
57
+ try:
58
+ window_size = 30
59
+
60
+ # Convert prediction_date to datetime
61
+ if isinstance(prediction_date, str):
62
+ prediction_date = datetime.strptime(prediction_date, '%Y-%m-%d')
63
+
64
+ print(f"\n{'='*80}")
65
+ print(f"PREDICTION REQUEST")
66
+ print(f"{'='*80}")
67
+ print(f"Miner: {miner_name}")
68
+ print(f"Region: {region}")
69
+ print(f"Date: {prediction_date.date()}")
70
+ print(f"{'='*80}\n")
71
+
72
+ # Get blockchain data for this specific date (30 days before + target date)
73
+ print(f"๐Ÿ“ก Fetching blockchain data for {prediction_date.date()}...")
74
+ blockchain_df = get_blockchain_data_for_date(prediction_date, window_size=window_size)
75
+
76
+ if blockchain_df is None or len(blockchain_df) < window_size:
77
+ error_msg = f"""
78
+ <div style='background: #e74c3c; color: white; padding: 20px; border-radius: 10px;'>
79
+ <h3 style='margin: 0;'>โŒ Error: Insufficient Data</h3>
80
+ <p style='margin: 10px 0 0 0;'>
81
+ Not enough blockchain data available for {prediction_date.date()}.
82
+ Need at least {window_size} days of historical data.
83
+ </p>
84
+ </div>
85
+ """
86
+ return error_msg, error_msg, None, None
87
+
88
+ print(f"โœ… Got {len(blockchain_df)} days of data")
89
+ print(f" Date range: {blockchain_df['date'].min().date()} to {blockchain_df['date'].max().date()}")
90
+
91
+ # Fetch ASIC price for the selected date
92
+ print(f"\n๐Ÿ’ฐ Fetching ASIC price for {prediction_date.date()}...")
93
+ miner_prices, data_available = fetch_asic_price_for_date(prediction_date)
94
+
95
+ if not data_available:
96
+ warning_html = f"""
97
+ <div style='background: #f39c12; color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;'>
98
+ <h3 style='margin: 0;'>โš ๏ธ Warning: Price Data Unavailable</h3>
99
+ <p style='margin: 10px 0 0 0;'>
100
+ No ASIC price data available for {prediction_date.date()}.
101
+ Using fallback prices (approximate market values).
102
+ </p>
103
+ </div>
104
+ """
105
+ else:
106
+ warning_html = ""
107
+
108
+ miner_price = miner_prices.get(miner_name, FALLBACK_PRICES.get(miner_name, 2500))
109
+ price_source = "API" if data_available else "Fallback"
110
+
111
+ print(f" Price for {miner_name}: ${miner_price:,.2f} ({price_source})")
112
+
113
+ # Get sequence (now uses blockchain_df which is date-specific)
114
+ print(f"\n๐Ÿ”ง Preparing features...")
115
+ sequence, _, pred_date = get_latest_sequence(blockchain_df, miner_name, miner_price, region, window_size)
116
+ print(f"โœ… Sequence prepared: {sequence.shape}")
117
+
118
+ # Predict
119
+ print(f"\n๐Ÿค– Running prediction...")
120
+ result = predictor.predict(sequence, region)
121
+ print(f"โœ… Prediction: {result['predicted_label']} ({result['confidence']:.1%})")
122
+
123
+ # Create displays
124
+ miner_info = create_miner_info(miner_name, miner_price, region, price_source, prediction_date)
125
+ prediction_html = warning_html + create_prediction_html(result, pred_date, window_size)
126
+ confidence_chart = create_confidence_chart(result['probabilities'])
127
+ price_chart = create_price_chart(blockchain_df, window_size)
128
+
129
+ print(f"{'='*80}\n")
130
+
131
+ return miner_info, prediction_html, confidence_chart, price_chart
132
+
133
+ except Exception as e:
134
+ import traceback
135
+ error_details = traceback.format_exc()
136
+ print(f"\nโŒ ERROR:")
137
+ print(error_details)
138
+
139
+ error = f"""
140
+ <div style='background: #e74c3c; color: white; padding: 20px; border-radius: 10px;'>
141
+ <h3 style='margin: 0;'>โŒ Prediction Error</h3>
142
+ <p style='margin: 10px 0 0 0;'>{str(e)}</p>
143
+ </div>
144
+ """
145
+ return error, error, None, None
146
+
147
+
148
+ def create_miner_info(miner_name, price, region, source, prediction_date):
149
+ specs = MINER_SPECS[miner_name]
150
+ # Daily electricity rate for the prediction date (with fallback beyond CSV range)
151
+ elec_rate = get_electricity_rate(region, prediction_date.date())
152
+ daily_cost = (specs['power'] * 24 / 1000) * elec_rate
153
+
154
+ # Color coding for source
155
+ if source == "API":
156
+ badge_color = "#27ae60" # Green
157
+ else:
158
+ badge_color = "#e74c3c" # Red for fallback
159
+
160
+ return f"""
161
+ <div style="background: #1e1e1e; padding: 20px; border-radius: 10px; border: 1px solid #333; color: #ffffff;">
162
+ <h3 style="color: #F7931A; margin-top: 0;">{specs['full_name']}</h3>
163
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
164
+ <div>
165
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Hashrate:</strong> {specs['hashrate']} TH/s</p>
166
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Power:</strong> {specs['power']} W</p>
167
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Efficiency:</strong> {specs['efficiency']} W/TH</p>
168
+ </div>
169
+ <div>
170
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Price ({prediction_date.date()}):</strong> ${price:,.2f}
171
+ <span style="background: {badge_color}; color: white; padding: 2px 8px; border-radius: 4px; font-size: 0.8em;">{source}</span>
172
+ </p>
173
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Region:</strong> {region.title()}</p>
174
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Electricity:</strong> ${elec_rate:.4f}/kWh</p>
175
+ </div>
176
+ </div>
177
+ <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #333;">
178
+ <p style="color: #ffffff;"><strong style="color: #ffffff;">Daily Electricity Cost:</strong> ${daily_cost:.2f}</p>
179
+ </div>
180
+ </div>
181
+ """
182
+
183
+
184
+ def create_prediction_html(result, date, window):
185
+ label = result['predicted_label']
186
+ conf = result['confidence']
187
+
188
+ if 'Unprofitable' in label:
189
+ color, emoji, rec = '#e74c3c', '๐Ÿ”ด', 'NOT RECOMMENDED'
190
+ elif 'Marginal' in label:
191
+ color, emoji, rec = '#f39c12', '๐ŸŸก', 'PROCEED WITH CAUTION'
192
+ else:
193
+ color, emoji, rec = '#27ae60', '๐ŸŸข', 'GOOD OPPORTUNITY'
194
+
195
+ return f"""
196
+ <div style="background: #1e1e1e; padding: 30px; border-radius: 10px; border: 2px solid {color}; text-align: center; color: #ffffff;">
197
+ <h2 style="color: {color}; margin: 0 0 10px 0;">{emoji} {label}</h2>
198
+ <p style="font-size: 1.2em; margin: 10px 0; color: #ffffff;"><strong style="color: #ffffff;">Confidence: {conf:.1%}</strong></p>
199
+ <p style="font-size: 1.5em; color: {color}; margin: 20px 0;"><strong style="color: {color};">{rec}</strong></p>
200
+ <p style="color: #cccccc; margin: 10px 0 0 0; font-size: 0.9em;">
201
+ Prediction based on data up to: {date.strftime('%Y-%m-%d')}<br>Window: {window} days
202
+ </p>
203
+ </div>
204
+ """
205
+
206
+
207
+ def create_confidence_chart(probs):
208
+ categories = ['Unprofitable', 'Marginal', 'Profitable']
209
+ values = [probs['unprofitable'], probs['marginal'], probs['profitable']]
210
+ colors = ['#e74c3c', '#f39c12', '#27ae60']
211
+
212
+ fig = go.Figure()
213
+ fig.add_trace(go.Bar(x=categories, y=values, marker_color=colors, text=[f'{v:.1%}' for v in values], textposition='auto'))
214
+ fig.update_layout(title='Prediction Confidence', yaxis_title='Probability', yaxis=dict(range=[0, 1], tickformat='.0%'),
215
+ template='plotly_dark', height=300, margin=dict(l=0, r=0, t=40, b=0))
216
+ return fig
217
+
218
+
219
+ def create_price_chart(df, window):
220
+ # Show more context if available
221
+ display_days = min(len(df), window * 2)
222
+ df_display = df.tail(display_days)
223
+
224
+ fig = go.Figure()
225
+ fig.add_trace(go.Scatter(x=df_display['date'], y=df_display['bitcoin_price'], mode='lines', name='Bitcoin Price', line=dict(color='#F7931A', width=2)))
226
+ fig.update_layout(title=f'Bitcoin Price ({len(df_display)} Days)', xaxis_title='Date', yaxis_title='Price (USD)',
227
+ template='plotly_dark', height=300, margin=dict(l=0, r=0, t=40, b=0))
228
+ return fig
229
+
230
+
231
+ def create_interface():
232
+ # Default date: today
233
+ today = datetime.now().date()
234
+
235
+ # Check if complete data is available to set min_date
236
+ complete_df = load_complete_blockchain_data()
237
+ if complete_df is not None:
238
+ min_date = complete_df['date'].min().date()
239
+ max_date = complete_df['date'].max().date()
240
+ date_info = f"{min_date} to {max_date}"
241
+ else:
242
+ min_date = datetime(2018, 1, 22).date()
243
+ max_date = today
244
+ date_info = "โš ๏ธ Limited (complete data not loaded)"
245
+
246
+ with gr.Blocks(title="MineROI-Net") as app:
247
+ gr.Markdown("# ๐Ÿช™ MineROI-Net: Bitcoin Mining Hardware ROI Predictor")
248
+ # gr.Markdown("### Powered by Complete Historical Blockchain Data")
249
+
250
+ with gr.Row():
251
+ with gr.Column(scale=1):
252
+ gr.Markdown("### Configuration")
253
+ miner = gr.Dropdown(choices=sorted(get_miner_list()), value='s19pro', label="ASIC Miner")
254
+ region = gr.Dropdown(choices=['texas', 'china', 'ethiopia'], value='texas', label="Region")
255
+
256
+ # Date picker for prediction date
257
+ prediction_date = gr.Textbox(
258
+ label="๐Ÿ“… Prediction Date",
259
+ value=str(today),
260
+ info=f"Format: YYYY-MM-DD (e.g., 2024-12-08)",
261
+ placeholder="2024-12-08",
262
+ elem_classes="date-input"
263
+ )
264
+
265
+ btn = gr.Button("๐Ÿ”ฎ Predict ROI", variant="primary", size="lg")
266
+
267
+ gr.Markdown(f"""
268
+ ### About
269
+ - ๐Ÿ”ด **Unprofitable** (ROI โ‰ค 0)
270
+ - ๐ŸŸก **Marginal** (0 < ROI < 1)
271
+ - ๐ŸŸข **Profitable** (ROI โ‰ฅ 1)
272
+
273
+ **Model:** 83.7% accuracy (30-day window)
274
+
275
+ **Date Range:** {date_info}
276
+
277
+ **Price Source:**
278
+ - ๐ŸŸข Green badge = Real API data
279
+ - ๐Ÿ”ด Red badge = Fallback estimate
280
+
281
+ **Data Source:**
282
+ - Uses complete historical blockchain data
283
+ - Loaded at app startup for fast predictions
284
+ """)
285
+
286
+ with gr.Column(scale=2):
287
+ gr.Markdown("### Results")
288
+ miner_info = gr.HTML()
289
+ prediction = gr.HTML()
290
+ with gr.Row():
291
+ conf_plot = gr.Plot()
292
+ price_plot = gr.Plot()
293
+
294
+ btn.click(fn=predict_roi, inputs=[miner, region, prediction_date], outputs=[miner_info, prediction, conf_plot, price_plot])
295
+
296
+ return app
297
+
298
+
299
+ if __name__ == "__main__":
300
+ # Initialize app (loads complete data into memory)
301
+ init_app()
302
+
303
+ # Launch
304
+ app = create_interface()
305
+ app.launch(server_name="0.0.0.0", server_port=7860, share=True)