REAVTO / app.py
testrro's picture
Create app.py
7a2e71e verified
import gradio as gr
import numpy as np
import pandas as pd
from datetime import datetime
import random
from collections import defaultdict
import math
import os
import traceback
# ==================== কনফিগারেশন ====================
CONFIG = {
"HISTORY_LIMIT": 1000,
"PINK_THRESHOLD": 3.0,
"BIG_PINK_THRESHOLD": 5.0,
}
# ==================== ডেটা লোড ও টাইম-ভিত্তিক পরিসংখ্যান ====================
TIME_STATS = None
def load_time_statistics():
global TIME_STATS
try:
# ডেটা ফাইলের পাথ
data_path = 'data/aviator_Rounds_history_scrp.xlsx'
if os.path.exists(data_path):
df = pd.read_excel(data_path, sheet_name='scraping rounds crash')
df = df[['ROUNDS', 'TIME ROUND']].dropna()
df['multiplier'] = pd.to_numeric(df['ROUNDS'], errors='coerce')
df = df.dropna()
df['hour'] = pd.to_datetime(df['TIME ROUND'], format='%H:%M').dt.hour
stats = df.groupby('hour')['multiplier'].agg(['mean', 'std', 'count']).to_dict('index')
for h in range(24):
if h not in stats:
stats[h] = {'mean': 1.8, 'std': 1.0, 'count': 0}
TIME_STATS = stats
print(f"✅ সময় পরিসংখ্যান লোড হয়েছে। মোট রেকর্ড: {len(df)}")
else:
print("⚠️ এক্সেল ফাইল পাওয়া যায়নি। ডিফল্ট পরিসংখ্যান ব্যবহার করা হবে।")
TIME_STATS = {h: {'mean': 1.8, 'std': 1.0, 'count': 100} for h in range(24)}
except Exception as e:
print(f"ডেটা লোড করতে সমস্যা: {e}")
TIME_STATS = {h: {'mean': 1.8, 'std': 1.0, 'count': 100} for h in range(24)}
load_time_statistics()
# ==================== স্ট্যাটিস্টিক্যাল মডেল V1-V5 ====================
class StatisticalModelV1:
"""V1: বেসিক স্ট্যাটিস্টিক্যাল + আউটলায়ার রিমুভাল"""
def predict(self, history):
recent = history[:15]
if len(recent) < 3:
return {'prediction': 1.5, 'confidence': 0.3}
# আউটলায়ার রিমুভাল (IQR)
q1, q3 = np.percentile(recent, [25, 75])
iqr = q3 - q1
filtered = [x for x in recent if (q1 - 1.5*iqr) <= x <= (q3 + 1.5*iqr)]
if len(filtered) < 3:
filtered = recent
# ওয়েটেড ট্রেন্ড
x = np.arange(len(filtered))
weights = np.linspace(1.5, 0.5, len(filtered))
weights /= weights.sum()
weighted_mean_x = np.average(x, weights=weights)
weighted_mean_y = np.average(filtered, weights=weights)
numerator = np.sum(weights * (x - weighted_mean_x) * (filtered - weighted_mean_y))
denominator = np.sum(weights * (x - weighted_mean_x)**2)
trend = numerator / denominator if denominator != 0 else 0
prediction = np.median(filtered) + trend * 1.5
# কনফিডেন্স
cv = np.std(filtered) / (np.mean(filtered) + 0.1)
confidence = min(0.85, 0.5 + len(filtered)/len(recent)*0.3 - cv*0.2)
return {'prediction': float(prediction), 'confidence': float(confidence)}
class StatisticalModelV2:
"""V2: মাল্টি-টাইমফ্রেম"""
def predict(self, history):
timeframes = {'short': history[:5], 'medium': history[:10], 'long': history[:20]}
preds, confs = [], []
for name, data in timeframes.items():
if len(data) < 3:
continue
ma_3 = np.mean(data[:3]) if len(data)>=3 else np.mean(data)
ma_5 = np.mean(data[:5]) if len(data)>=5 else ma_3
ema = data[0]
alpha = 0.3
for v in data[1:]:
ema = alpha*v + (1-alpha)*ema
x = np.arange(len(data))
trend = np.polyfit(x, data, 1)[0]
base = np.mean([ma_3, ma_5, ema])
preds.append(base + trend * len(data) / 10)
confs.append(min(0.9, 0.5 + len(data)/40))
if not preds:
return {'prediction': 1.5, 'confidence': 0.3}
weights = {'short':0.5, 'medium':0.3, 'long':0.2}
final_pred = 0
total_weight = 0
for i, name in enumerate(timeframes.keys()):
if i < len(preds):
w = weights.get(name, 0.2) * confs[i]
final_pred += preds[i] * w
total_weight += w
final_pred /= total_weight if total_weight else 1
confidence = np.mean(confs) * 0.9
return {'prediction': float(final_pred), 'confidence': float(confidence)}
class StatisticalModelV3:
"""V3: সাইকেল ডিটেকশন"""
def detect_cycles(self, history):
if len(history) < 10:
return None
cycles = []
for period in range(3, 7):
corrs = []
for i in range(len(history) - period*2):
seg1 = history[i:i+period]
seg2 = history[i+period:i+period*2]
if len(seg1) == len(seg2):
corr = np.corrcoef(seg1, seg2)[0,1]
if not np.isnan(corr):
corrs.append(abs(corr))
if corrs and np.mean(corrs) > 0.6:
cycles.append({'period': period, 'strength': float(np.mean(corrs))})
return cycles if cycles else None
def predict(self, history):
recent = history[:20]
cycles = self.detect_cycles(recent)
cycle_pred = None
if cycles:
best = max(cycles, key=lambda x: x['strength'])
period = best['period']
if len(recent) > period:
next_val = recent[period:period+1]
if next_val:
cycle_pred = next_val[0] * (1 + best['strength'] * 0.1)
base_pred = np.median(recent)
if cycle_pred:
base_pred = (base_pred + cycle_pred) / 2
prediction = max(1.05, min(12.0, base_pred))
confidence = min(0.9, 0.5 + len(recent)/40 + (0.15 if cycles else 0))
return {'prediction': float(prediction), 'confidence': float(confidence)}
class StatisticalModelV4:
"""V4: এডাপটিভ লার্নিং"""
def __init__(self):
self.performance = []
self.bias = 0
self.volatility_regime = 'normal'
def detect_volatility(self, history):
if len(history) < 10:
return 'normal'
recent_vol = np.std(history[:5])
long_vol = np.std(history[:20]) if len(history)>=20 else recent_vol
if recent_vol > long_vol * 1.5:
return 'high'
elif recent_vol < long_vol * 0.5:
return 'low'
else:
return 'normal'
def predict(self, history):
recent = history[:15]
self.volatility_regime = self.detect_volatility(history)
mean_val, median_val = np.mean(recent), np.median(recent)
x = np.arange(len(recent))
weights = np.exp(-0.2 * x)
weights /= weights.sum()
weighted_mean_x = np.average(x, weights=weights)
weighted_mean_y = np.average(recent, weights=weights)
numerator = np.sum(weights * (x - weighted_mean_x) * (recent - weighted_mean_y))
denominator = np.sum(weights * (x - weighted_mean_x)**2)
trend = numerator / denominator if denominator != 0 else 0
preds = {'mean': mean_val, 'median': median_val, 'trend': median_val + trend * len(recent) * 0.5}
w = {'mean': 0.3, 'median': 0.4, 'trend': 0.3}
if self.volatility_regime == 'high':
w['median'] *= 1.5
elif self.volatility_regime == 'low':
w['trend'] *= 1.3
total = sum(w.values())
for k in w:
w[k] /= total
prediction = sum(preds[k] * w[k] for k in preds) + self.bias
confidence = 0.5 + len(recent)/30
if self.volatility_regime == 'high':
confidence *= 0.8
elif self.volatility_regime == 'low':
confidence *= 1.2
if self.performance:
recent_perf = np.mean(self.performance[-10:]) if len(self.performance)>=10 else np.mean(self.performance)
confidence *= (1 + recent_perf * 0.1)
confidence = min(0.9, confidence)
return {'prediction': float(max(1.05, min(12.0, prediction))), 'confidence': float(confidence)}
def update(self, actual, predicted):
error = abs(actual - predicted) / actual
acc = max(0, 1 - error)
self.performance.append(acc)
if len(self.performance) > 100:
self.performance = self.performance[-100:]
self.bias += (actual - predicted) * 0.01
class StatisticalModelV5:
"""V5: র‍্যান্ডম ফরেস্ট সিমুলেশন"""
def __init__(self):
self.n_estimators = 10
def predict(self, history):
if len(history) < 10:
return {'prediction': 1.5, 'confidence': 0.5}
recent = history[:10]
trees = []
for _ in range(self.n_estimators):
idx = np.random.choice(len(recent), size=len(recent), replace=True)
sample = [recent[i] for i in idx]
if np.random.random() > 0.5:
trees.append(np.mean(sample))
else:
trees.append(np.median(sample))
pred = float(np.mean(trees))
return {'prediction': pred, 'confidence': 0.7}
# ==================== V6 মডেল (টাইম-ভিত্তিক) ====================
class StatisticalModelV6:
"""V6: টাইম-অফ-ডে অ্যাডজাস্টমেন্ট"""
def __init__(self, time_stats):
self.time_stats = time_stats
def predict(self, history, current_hour=None):
if current_hour is None:
current_hour = datetime.now().hour
stats = self.time_stats.get(current_hour, {'mean': 1.8, 'std': 1.0})
base_pred = np.median(history[:5]) if len(history)>=5 else 1.5
alpha = 0.3
prediction = base_pred * (1 - alpha) + stats['mean'] * alpha
confidence = min(0.85, 0.5 + stats.get('count', 100) / 500)
return {'prediction': float(prediction), 'confidence': float(confidence), 'hour': current_hour}
# ==================== এনসেম্বল প্রেডিক্টর ====================
class EnsemblePredictorV6:
def __init__(self, time_stats):
self.models = {
'v1': StatisticalModelV1(),
'v2': StatisticalModelV2(),
'v3': StatisticalModelV3(),
'v4': StatisticalModelV4(),
'v5': StatisticalModelV5(),
'v6': StatisticalModelV6(time_stats)
}
self.ensemble_weights = {'v1':0.2, 'v2':0.2, 'v3':0.15, 'v4':0.15, 'v5':0.15, 'v6':0.15}
self.performance = defaultdict(list)
def predict(self, history):
if len(history) < 5:
return self._default_prediction(f"মাত্র {len(history)}টি রাউন্ড, ৫টি প্রয়োজন")
current_hour = datetime.now().hour
preds = {}
confs = {}
for name, model in self.models.items():
if name == 'v6':
res = model.predict(history, current_hour)
else:
res = model.predict(history)
preds[name] = res['prediction']
confs[name] = res.get('confidence', 0.5)
# ওয়েট আপডেট
for name in self.ensemble_weights:
if name in self.performance and self.performance[name]:
recent_acc = np.mean(self.performance[name][-20:]) if len(self.performance[name])>=20 else np.mean(self.performance[name])
self.ensemble_weights[name] = 0.1 + recent_acc * 0.8
total = sum(self.ensemble_weights.values())
for name in self.ensemble_weights:
self.ensemble_weights[name] /= total
final_pred = 0
total_weight = 0
for name, pred in preds.items():
weight = self.ensemble_weights.get(name, 0.2) * confs[name]
final_pred += pred * weight
total_weight += weight
final_pred /= total_weight if total_weight else 1
# মার্কেট স্টেট
recent = history[:10]
vol = np.std(recent) / (np.mean(recent)+0.1)
if vol > 0.5:
state = "অস্থির 🌪️"
elif vol < 0.2:
state = "স্থিতিশীল ✨"
else:
state = "সাধারণ ➡️"
confidence = np.mean(list(confs.values())) * 0.9
if vol < 0.2:
confidence *= 1.1
elif vol > 0.5:
confidence *= 0.9
confidence = min(0.95, confidence)
# প্রেডিকশন ইন্টারভ্যাল
all_preds = list(preds.values())
std = np.std(all_preds) if len(all_preds)>1 else 0.2
spread = std * (2 - confidence)
spread = max(0.1, min(1.5, spread))
interval = (max(1.01, final_pred - spread/2), final_pred + spread/2)
# ডিসিশন
if final_pred > 3.0:
decision = "বড় 🚀"
elif final_pred > 1.8:
decision = "মাঝারি 💪"
else:
decision = "ছোট 🎯"
hour_stats = TIME_STATS.get(current_hour, {'mean':1.8, 'count':0})
time_info = f"বর্তমান ঘণ্টা: {current_hour}:00 – ঐতিহাসিক গড়: {hour_stats['mean']:.2f}x (ডাটা: {hour_stats['count']}টি)"
summary = (
f"🎯 **প্রেডিকশন ইন্টারভ্যাল**: {interval[0]:.2f}x – {interval[1]:.2f}x\n"
f"📊 **এক্সপেক্টেড মাল্টিপ্লায়ার**: {final_pred:.2f}x\n"
f"📈 **কনফিডেন্স**: {confidence*100:.1f}%\n"
f"⚡ **মার্কেট স্টেট**: {state}\n"
f"🎲 **ডিসিশন**: {decision}\n"
f"⏰ **টাইম ফিচার**: {time_info}\n"
f"📌 **ডাটা পয়েন্ট**: {len(history)}টি রাউন্ড"
)
return {
'summary': summary,
'prediction': final_pred,
'interval': interval,
'confidence': confidence,
'decision': decision,
'analysis': state,
'hour': current_hour
}
def _default_prediction(self, msg):
return {
'summary': f"⚠️ {msg}\n\n📊 ডিফল্ট প্রেডিকশন: 1.50x (কনফিডেন্স 30%)",
'prediction': 1.5,
'interval': (1.3, 1.7),
'confidence': 0.3,
'decision': 'ছোট 🎯',
'analysis': 'অপ্রতুল ডাটা'
}
# ==================== অ্যাপ্লিকেশন ক্লাস ====================
class AviatorPredictorApp:
def __init__(self):
self.history = []
self.model = EnsemblePredictorV6(TIME_STATS)
def add_round(self, multiplier):
if multiplier <= 0:
return self.get_all_outputs(error="ইনভ্যালিড মাল্টিপ্লায়ার (১.০ এর বেশি দিন)")
self.history.insert(0, float(multiplier))
if len(self.history) > CONFIG["HISTORY_LIMIT"]:
self.history = self.history[:CONFIG["HISTORY_LIMIT"]]
return self.get_all_outputs()
def reset(self):
self.history = []
for _ in range(20):
self.history.append(round(random.uniform(1.0, 3.5), 2))
self.history.sort(reverse=True)
return self.get_all_outputs()
def get_all_outputs(self, error=None):
if error:
table = [[i+1, "?.??x"] for i in range(min(20, len(self.history)))] or [[1, "1.00x"]]
return [table, f"⚠️ {error}"]
pred_result = self.model.predict(self.history)
table = [[i+1, f"{val:.2f}x"] for i, val in enumerate(self.history[:50])]
return [table, pred_result['summary']]
# ==================== কাস্টম CSS ====================
CUSTOM_CSS = """
.gradio-container {
background: #0a0a0f !important;
color: #ffffff !important;
font-family: 'Inter', sans-serif !important;
}
footer {visibility: hidden}
h1 {
color: #00d4ff !important;
text-align: center;
margin-bottom: 20px;
text-shadow: 0 0 10px #00d4ff;
}
.gr-box {
border: 1px solid #333 !important;
background: rgba(255,255,255,0.05) !important;
}
.gr-button-primary {
background: linear-gradient(135deg, #00d4ff, #0088ff) !important;
border: none !important;
}
.gr-button-secondary {
background: rgba(255,255,255,0.1) !important;
border: 1px solid #00d4ff !important;
margin-top: 20px !important;
}
.gr-dataframe {
background: rgba(255,255,255,0.05) !important;
}
"""
# ==================== গ্র্যাডিও ইন্টারফেস ====================
app = AviatorPredictorApp()
app.reset()
with gr.Blocks(css=CUSTOM_CSS, theme='dark', title="AVOLD V6 Predictor") as demo:
gr.HTML("""
<div style="text-align: center; margin-bottom: 20px;">
<h1 style="color: #00d4ff; font-size: 48px; margin: 0;">✈️ AVOLD V6</h1>
<p style="color: #888; font-size: 14px;">সময়-ভিত্তিক এভিয়েটর প্রেডিক্টর – ৬টি মডেলের এনসেম্বল</p>
</div>
""")
with gr.Row():
inp = gr.Number(label="নতুন মাল্টিপ্লায়ার", value=1.0, step=0.1, minimum=1.0)
add_btn = gr.Button("➕ যোগ করুন", variant="primary")
prediction_box = gr.Textbox(label="🧠 প্রেডিকশন রিপোর্ট", lines=10, interactive=False)
rounds_table = gr.Dataframe(label="📜 শেষ ৫০ রাউন্ড", headers=["রাউন্ড", "মাল্টিপ্লায়ার"], row_count=10)
reset_btn = gr.Button("🔄 রিসেট ডাটা", variant="secondary")
add_btn.click(
fn=app.add_round,
inputs=inp,
outputs=[rounds_table, prediction_box]
)
reset_btn.click(
fn=app.reset,
outputs=[rounds_table, prediction_box]
)
demo.load(
fn=app.get_all_outputs,
outputs=[rounds_table, prediction_box]
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)