Spaces:
Running
Running
| 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 | |
| import matplotlib.pyplot as plt | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| # Настройка логирования | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # Определение размера изображения | |
| 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" | |
| ) | |
| # Загружаем файл с кастомными слоями | |
| layers_path = hf_hub_download( | |
| repo_id="Dianor/trading-model-private", | |
| filename="custom_trading_layers.py" | |
| ) | |
| 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 | |
| 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 | |
| ) |