File size: 8,992 Bytes
47c13b8
 
 
d2365b3
 
24c2743
7c29c5b
24c2743
282225d
e45b035
 
 
 
 
 
 
 
2b533d2
282225d
d2365b3
 
 
e45b035
 
 
 
 
 
d2365b3
e45b035
 
 
c20d965
e45b035
e4d41fb
e45b035
d2365b3
e45b035
2b533d2
 
e45b035
24c2743
e45b035
24c2743
e45b035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51ec336
d2365b3
e45b035
 
 
 
24c2743
e45b035
 
c20d965
e45b035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9affaa9
c20d965
e45b035
 
 
 
 
2b533d2
 
c20d965
24c2743
 
e45b035
 
24c2743
c20d965
d2365b3
 
 
 
 
e45b035
d2365b3
c20d965
24c2743
e45b035
 
24c2743
 
 
e45b035
 
 
c20d965
e45b035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c20d965
e45b035
 
 
 
 
 
 
 
c20d965
e45b035
 
 
 
 
 
 
 
 
 
 
47c13b8
c20d965
24c2743
e45b035
d2365b3
2b533d2
e45b035
c20d965
e45b035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b533d2
e45b035
2b533d2
51ec336
c20d965
e45b035
24c2743
37756a8
24c2743
e45b035
24c2743
c20d965
24c2743
e45b035
 
 
 
 
 
 
 
 
 
51ec336
24c2743
 
e45b035
c20d965
7c29c5b
51ec336
47c13b8
d2365b3
e45b035
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
import gradio as gr
import cv2
import numpy as np
from PIL import Image, ImageDraw
import warnings
import io
import torch
import base64
import os
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.cluster import DBSCAN
from transformers import (
    AutoModelForObjectDetection,
    DetrImageProcessor,
    pipeline
)
from huggingface_hub import InferenceClient

warnings.filterwarnings("ignore")

# Constants
MAX_SIZE = 1024
CLAHE_CLIP = 3.0
CANNY_THRESHOLDS = (50, 200)
HOUGH_PARAMS = (50, 30, 50)
DBSCAN_EPS = 10.0
MIN_SAMPLES = 5

# CPU optimizations
os.environ["OMP_NUM_THREADS"] = str(os.cpu_count() or 8)
torch.set_num_threads(os.cpu_count() or 8)

# Model configurations
DETECTION_MODEL = "facebook/detr-resnet-50"
LLM_MODEL_NAME = "meta-llama/Meta-Llama-3-70B-Instruct"

# Initialize models
detection_processor = DetrImageProcessor.from_pretrained(DETECTION_MODEL)
detection_model = AutoModelForObjectDetection.from_pretrained(DETECTION_MODEL)
llm_client = InferenceClient(model=LLM_MODEL_NAME, token=os.getenv("HF_TOKEN"))

# Enhanced system prompt
SYSTEM_PROMPT = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>
You are a senior cryptocurrency trading analyst with 15 years experience. Analyze the following comprehensive chart data:

Technical Elements Detected:
{technical_analysis}

User Query: {question}

Provide detailed professional analysis covering:
1. Price Action Analysis (Trend Strength, Momentum)
2. Key Support/Resistance Zones (Cluster Analysis)
3. Volume-Weighted Price Levels
4. Pattern Recognition (Continuation/Reversal)
5. Fibonacci Retracement Levels (if applicable)
6. Market Structure Analysis
7. Risk/Reward Ratios
8. Optimal Trade Entry/Exit Strategies

Include statistical confidence levels for each analysis component. Format response in markdown with mathematical notations where appropriate.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""

def adaptive_resize(image):
    height, width = image.size
    scale = MAX_SIZE / max(height, width)
    return image.resize((int(width*scale), int(height*scale)), Image.LANCZOS)

def enhance_contrast(img):
    lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
    l, a, b = cv2.split(lab)
    clahe = cv2.createCLAHE(clipLimit=CLAHE_CLIP, tileGridSize=(8,8))
    limg = clahe.apply(l)
    merged = cv2.merge([limg, a, b])
    return cv2.cvtColor(merged, cv2.COLOR_LAB2RGB)

def detect_lines(image):
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    edges = cv2.Canny(gray, *CANNY_THRESHOLDS)
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, *HOUGH_PARAMS)
    return lines

def cluster_lines(lines):
    if lines is None:
        return []
    points = lines.reshape(-1, 2)
    clustering = DBSCAN(eps=DBSCAN_EPS, min_samples=MIN_SAMPLES).fit(points)
    return clustering.labels_

def calculate_slope(line):
    x1, y1, x2, y2 = line
    return (y2 - y1) / (x2 - x1) if (x2 - x1) != 0 else np.inf

def detect_key_levels(image):
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    hist = cv2.calcHist([gray], [0], None, [256], [0,256])
    peaks, _ = find_peaks(hist.flatten(), distance=10, prominence=50)
    return [p for p in peaks if 10 < p < 240]

def analyze_volume_profile(image):
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    return cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

def detect_candlesticks(image):
    edges = cv2.Canny(image, 50, 150)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    candles = []
    for cnt in contours:
        x,y,w,h = cv2.boundingRect(cnt)
        if 5 < w < 50 and 10 < h < 200:
            candles.append((x,y,w,h))
    return candles

def detect_chart_elements(image):
    image_np = np.array(image)
    enhanced = enhance_contrast(image_np)
    
    # Deep Learning Detection
    inputs = detection_processor(images=Image.fromarray(enhanced), return_tensors="pt")
    with torch.no_grad():
        outputs = detection_model(**inputs)
    
    results = detection_processor.post_process_object_detection(
        outputs, 
        target_sizes=torch.tensor([image.size[::-1]]),
        threshold=0.85
    )[0]
    
    elements = {
        'support_resistance': [],
        'trendlines': [],
        'patterns': [],
        'candlesticks': [],
        'indicators': []
    }
    
    draw = ImageDraw.Draw(image)
    
    # Process DL detections
    for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        box = [round(i, 2) for i in box.tolist()]
        label_name = detection_model.config.id2label[label.item()]
        elements['patterns' if 'pattern' in label_name else 'indicators'].append(label_name)
        draw.rectangle(box, outline="#FF0000", width=3)
        draw.text((box[0], box[1]), f"{label_name} ({score:.2f})", fill="#FF0000")
    
    # Traditional CV Detection
    lines = detect_lines(enhanced)
    if lines is not None:
        clusters = cluster_lines(lines)
        for i, line in enumerate(lines):
            x1, y1, x2, y2 = line[0]
            slope = calculate_slope(line[0])
            length = np.sqrt((x2-x1)**2 + (y2-y1)**2)
            
            if abs(slope) < 0.1 and length > 100:
                elements['support_resistance'].append(f"Key Level at y={y1}")
                draw.line((x1, y1, x2, y2), fill="#00FF00", width=3)
            elif 0.1 < abs(slope) < 5:
                elements['trendlines'].append(f"Trendline ({'Up' if slope < 0 else 'Down'})")
                draw.line((x1, y1, x2, y2), fill="#0000FF", width=3)
    
    # Volume Profile Analysis
    volume_profile = analyze_volume_profile(enhanced)
    contours, _ = cv2.findContours(volume_profile, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        if cv2.contourArea(cnt) > 1000:
            x,y,w,h = cv2.boundingRect(cnt)
            elements['support_resistance'].append(f"Volume Cluster at {y+h//2}")
            draw.rectangle([x,y,x+w,y+h], outline="#FFA500", width=2)
    
    return image, elements

def generate_technical_report(elements):
    report = []
    if elements['support_resistance']:
        report.append("**Key Levels**: " + ", ".join(elements['support_resistance'][:5]))
    if elements['trendlines']:
        report.append("**Trend Analysis**: " + ", ".join(elements['trendlines']))
    if elements['patterns']:
        report.append("**Chart Patterns**: " + ", ".join(elements['patterns']))
    return "\n".join(report)

def respond(message, history, image):
    if image is None:
        return "Please upload a cryptocurrency chart for analysis."
    
    try:
        processed_img = adaptive_resize(image)
        annotated_img, elements = detect_chart_elements(processed_img)
        tech_report = generate_technical_report(elements)
        
        full_prompt = SYSTEM_PROMPT.format(
            technical_analysis=tech_report,
            question=message
        )
        
        response = llm_client.text_generation(
            full_prompt,
            max_new_tokens=1500,
            temperature=0.1,
            repetition_penalty=1.1,
            seed=42
        )
        
        img_base64 = base64.b64encode(annotated_img.tobytes()).decode('utf-8')
        img_html = f'<div style="border: 2px solid #4CAF50; padding: 10px; margin-bottom: 20px;">' \
                   f'<img src="data:image/png;base64,{img_base64}" style="max-width: 100%;">' \
                   f'</div>'
        
        return f"{img_html}\n{response.split('<|assistant|>')[-1].strip()}"
    
    except Exception as e:
        return f"⚠️ Advanced Analysis Error: {str(e)}"

demo = gr.ChatInterface(
    fn=respond,
    additional_inputs=[gr.Image(label="Upload Crypto Chart", type="pil")],
    chatbot=gr.Chatbot(
        avatar_images=["user.png", "ai.png"],
        show_copy_button=True,
        layout="bubble",
        bubble_full_width=False,
        sanitize_html=False
    ),
    title="CryptoQuantum Analyst Pro",
    description="""<div style="text-align: center; border-bottom: 3px solid #4CAF50; padding: 20px;">
                 <h1>πŸͺ™ CryptoQuantum Analyst Pro</h1>
                 <p>Advanced AI-powered Cryptocurrency Technical Analysis System</p>
                 <div style="display: flex; justify-content: center; gap: 15px; margin-top: 10px;">
                     <div style="background: #4CAF5050; padding: 10px; border-radius: 5px;">πŸ“ˆ Multi-Timeframe Analysis</div>
                     <div style="background: #4CAF5050; padding: 10px; border-radius: 5px;">πŸ” Deep Pattern Recognition</div>
                     <div style="background: #4CAF5050; padding: 10px; border-radius: 5px;">πŸ€– Neural Market Forecasting</div>
                 </div>
                 </div>""",
    theme="Nymbo/Nymbo_Theme",
    textbox=gr.Textbox(
        label="Ask Technical Questions",
        placeholder="Enter your crypto analysis questions...",
        container=False
    )
)

if __name__ == "__main__":
    demo.launch()