Spaces:
Running
Running
File size: 12,893 Bytes
ffd16f3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
import os
import gradio as gr
import tensorflow as tf
import numpy as np
import cv2
from PIL import Image
import logging
from huggingface_hub import hf_hub_download
from huggingface_hub import login
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Проверка наличия токена
if "HUGGINGFACE_TOKEN" not in os.environ:
logger.error("HUGGINGFACE_TOKEN not found in environment variables!")
else:
logger.info("HUGGINGFACE_TOKEN found")
# Аутентификация с использованием токена
login(token=os.environ["HUGGINGFACE_TOKEN"])
logger.info("Logged in to Hugging Face")
# Определение размера изображения
IMG_SHAPE = (479, 1221, 3)
class SecureModel:
_instance = None
def __init__(self):
try:
logger.info("Attempting to download model files...")
# Загружаем файл модели
model_path = hf_hub_download(
repo_id="Dianor/trading-model-private",
filename="trading_modelbeta0.7.keras",
token=os.environ["HUGGINGFACE_TOKEN"]
)
# Загружаем файл с кастомными слоями
layers_path = hf_hub_download(
repo_id="Dianor/trading-model-private",
filename="custom_trading_layers.py",
token=os.environ["HUGGINGFACE_TOKEN"]
)
logger.info(f"Files downloaded successfully")
# Импортируем кастомные слои из скачанного модуля
import importlib.util
import sys
# Загружаем модуль с кастомными слоями
spec = importlib.util.spec_from_file_location("custom_trading_layers", layers_path)
custom_module = importlib.util.module_from_spec(spec)
sys.modules["custom_trading_layers"] = custom_module
spec.loader.exec_module(custom_module)
# Получаем словарь custom_objects
custom_objects = custom_module.get_custom_objects()
# Обновляем глобальные объекты TensorFlow
tf.keras.utils.get_custom_objects().update(custom_objects)
# Загружаем модель
try:
self.model = tf.keras.models.load_model(
model_path,
custom_objects=custom_objects,
compile=False
)
except Exception as load_error:
logger.warning(f"Direct load failed: {load_error}")
self.model = tf.keras.models.load_model(
model_path,
custom_objects=custom_objects,
compile=False
)
self.model.compile(
optimizer='adam',
loss={
'long_signal': 'binary_crossentropy',
'short_signal': 'binary_crossentropy'
},
metrics=['accuracy']
)
logger.info("Model loaded successfully")
except Exception as e:
logger.error(f"Failed to load model: {str(e)}")
raise
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance.model
def preprocess_image(image):
try:
logger.info(f"Starting preprocessing. Input shape: {image.shape}")
# Конвертируем в RGB если нужно (если изображение в BGR)
if len(image.shape) == 3 and image.shape[2] == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (IMG_SHAPE[1], IMG_SHAPE[0]))
# Используем ту же нормализацию
image = image.astype('float32') / 255.0
logger.info(f"Preprocessed shape: {image.shape}")
logger.info(f"Value range: [{image.min():.3f}, {image.max():.3f}]")
return image
except Exception as e:
logger.error(f"Error in preprocess_image: {str(e)}")
raise
def analyze_trading_chart(input_image):
try:
model = SecureModel.get_instance()
# Сохраняем оригинал для отображения
display_image = input_image.copy()
# Логируем исходное изображение
logger.info(f"Raw input shape: {input_image.shape}")
logger.info(f"Raw input range: [{input_image.min()}, {input_image.max()}]")
# Изменяем размер изображения до требуемого
resized_image = cv2.resize(input_image, (1221, 479), interpolation=cv2.INTER_NEAREST)
# Нормализуем изображение
image = resized_image.astype('float32') / 255.0
image = np.expand_dims(image, axis=0) # Добавляем batch dimension
# Логируем после обработки
logger.info(f"Processed input shape: {image.shape}")
logger.info(f"Processed input range: [{image.min():.3f}, {image.max():.3f}]")
# Делаем предсказание
predictions = model.predict(image, verbose=0)
# Логируем сырые предсказания
logger.info(f"Raw predictions: {predictions}")
long_signal = float(predictions['long_signal'][0][0])
short_signal = float(predictions['short_signal'][0][0])
logger.info(f"Final predictions: LONG={long_signal:.3f}, SHORT={short_signal:.3f}")
# Создаем визуализацию
plt.style.use('dark_background')
fig = plt.figure(figsize=(15, 10), facecolor='#1E222D')
gs = fig.add_gridspec(2, 1, height_ratios=[3, 1], hspace=0.3)
# График цены
ax1 = fig.add_subplot(gs[0])
ax1.imshow(display_image) # Показываем оригинальное изображение
ax1.set_title('Trading Chart Analysis', color='#B7BDD7', pad=10, fontsize=14)
ax1.axis('off')
# Панель сигналов
ax2 = fig.add_subplot(gs[1])
ax2.set_facecolor('#1E222D')
bar_positions = [0, 1]
signal_values = [long_signal, short_signal]
colors = ['#26a69a', '#ef5350']
labels = ['Long Signal', 'Short Signal']
bars = ax2.bar(bar_positions, signal_values, color=colors)
ax2.set_xticks(bar_positions)
ax2.set_xticklabels(labels, color='#B7BDD7', fontsize=12)
ax2.set_ylim(0, 1)
ax2.set_ylabel('Signal Strength', color='#B7BDD7', fontsize=12)
ax2.grid(True, alpha=0.2)
ax2.tick_params(colors='#B7BDD7')
# Добавляем значения над барами
for bar in bars:
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.3f}',
ha='center', va='bottom', color='#B7BDD7',
fontsize=12)
ax2.axhline(y=0.8, color='white', linestyle='--', alpha=0.5, label='Signal Threshold')
ax2.legend(loc='upper right', bbox_to_anchor=(0.98, 0.98))
# Конвертируем график в изображение
fig.canvas.draw()
buf = fig.canvas.buffer_rgba()
img = np.asarray(buf)
plt.close(fig)
return img
except Exception as e:
logger.error(f"Error in analyze_trading_chart: {str(e)}")
logger.exception("Full traceback:")
return display_image
# Создаем интерфейс с табами
def create_interface():
with gr.Blocks(theme=gr.themes.Default()) as demo:
gr.Markdown("""
# 🚀 Revolutionary Neural Vision Trading
## Next-Generation AI Computer Vision for Cryptocurrency Trading
Introducing the world's first neural network that trades cryptocurrency through pure visual comprehension—a breakthrough technology that sees charts just like professional traders do.
This revolutionary AI doesn't rely on traditional indicators or mathematical patterns. Instead, it employs advanced computer vision to interpret market dynamics visually, analyzing real-time price action with human-like perception but machine-level precision.
The system provides confidence-based entry signals, automatically executing trades when conviction reaches 0.9 or higher—mimicking the decision-making process of elite traders while eliminating emotional bias.
---
### Unprecedented Market Understanding:
❗️ Visual price action analysis based on pure Computer Vision
❗️ Dynamic support/resistance identification through visual context
❗️ Real-time decision making focused on the critical last candle
---
Try it now! Upload your TradingView/Binance dark theme chart, or use our examples and experience trading intelligence that exists nowhere else in the market.
**💼 Limited partnership opportunities available for qualified investors. Contact us to join the visual trading revolution.**
""")
with gr.Tabs():
# Таб анализа графиков
with gr.Tab("Signal Analysis"):
with gr.Row():
# Левая колонка для ввода
with gr.Column(scale=1):
gr.Markdown("""
### Upload Your Trading Chart
Or use example charts below
""")
input_image = gr.Image(type="numpy", height=400)
# Правая колонка для вывода
with gr.Column(scale=1):
gr.Markdown("""
### Analysis Results
- Long Signal (Green): Upward movement probability
- Short Signal (Red): Downward movement probability
""")
output_image = gr.Image(type="numpy", height=400)
analyze_btn = gr.Button("Analyze Chart", size="lg")
analyze_btn.click(
fn=analyze_trading_chart,
inputs=input_image,
outputs=output_image
)
gr.Markdown("### Example Charts")
gr.Examples(
examples=[
"example1.png", "example2.png", "example3.png", "example4.png",
"example5.png", "example6.png", "example7.png", "example8.png",
"example9.png", "example10.png"
],
inputs=input_image,
outputs=output_image,
fn=analyze_trading_chart,
cache_examples=True,
examples_per_page=10
)
# Таб с демонстрационным видео
with gr.Tab("Trading Demo"):
gr.Markdown("""
## Trading System Backtesting Demo
Watch how our AI trading system performs in different market conditions.
""")
with gr.Row():
with gr.Column(scale=1, min_width=800):
gr.Video("demo.mp4")
gr.Markdown("""
### What you're seeing in the demo:
- Real-time trading decisions
- Signal generation and execution
- Performance metrics and profit visualization
- Risk management in action
""")
return demo
if __name__ == "__main__":
try:
logger.info("Initializing model at startup...")
SecureModel.get_instance()
logger.info("Model initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize model at startup: {str(e)}")
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
) |