aidevhund commited on
Commit
e45b035
·
verified ·
1 Parent(s): c20d965

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +175 -110
app.py CHANGED
@@ -1,99 +1,130 @@
1
  import gradio as gr
2
  import cv2
3
  import numpy as np
4
- from transformers import (
5
- AutoModelForObjectDetection,
6
- DetrImageProcessor
7
- )
8
  from PIL import Image, ImageDraw
9
  import warnings
10
  import io
11
  import torch
12
  import base64
13
  import os
 
 
 
 
 
 
 
 
14
  from huggingface_hub import InferenceClient
15
 
16
- ACCESS_TOKEN = os.getenv("HF_TOKEN")
17
-
18
  warnings.filterwarnings("ignore")
19
 
20
  # Constants
21
- MAX_WIDTH = 800
22
- MAX_HEIGHT = 600
 
 
 
 
23
 
24
- # CPU optimizasyonları
25
- os.environ["OMP_NUM_THREADS"] = str(os.cpu_count() or 4)
 
26
 
27
- # Model ve InferenceClient ayarları
28
- DETECTION_MODEL = "facebook/detr-resnet-50"
29
- LLM_MODEL_NAME = "meta-llama/Llama-3.1-8B-Instruct"
30
 
31
- # Detection model ve processor
32
  detection_processor = DetrImageProcessor.from_pretrained(DETECTION_MODEL)
33
  detection_model = AutoModelForObjectDetection.from_pretrained(DETECTION_MODEL)
 
34
 
35
- # InferenceClient for LLM
36
- llm_client = InferenceClient(
37
- model=LLM_MODEL_NAME,
38
- token=ACCESS_TOKEN
39
- )
40
-
41
- # Optimize edilmiş sistem prompt
42
  SYSTEM_PROMPT = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>
43
- You are a professional financial analyst specializing in cryptocurrency technical analysis.
44
- Analyze the following chart elements and provide a detailed report:
45
- <|eot_id|><|start_header_id|>user<|end_header_id|>
46
- Chart Elements Detected:
47
- - Support/Resistance: {support_resistance}
48
- - Trendlines: {trendlines}
49
- - Patterns: {patterns}
50
- - Candlestick formations: {candlesticks}
51
- User Question: {question}
52
- Provide analysis covering:
53
- 1. Trend analysis (primary and secondary trends)
54
- 2. Key support/resistance levels
55
- 3. Detected chart patterns
56
- 4. Candlestick formations
57
- 5. Volume analysis
58
- 6. Trading signals with confidence levels
59
- 7. Risk management suggestions
60
- Format response in markdown with clear sections using professional trading terminology.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
61
  """
62
 
63
- # Yardımcı fonksiyonlar
64
- def image_to_base64(img):
65
- buffered = io.BytesIO()
66
- img.save(buffered, format="PNG")
67
- return base64.b64encode(buffered.getvalue()).decode("utf-8")
68
 
69
- def preprocess_image(image):
70
- img = np.array(image)
71
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
72
-
73
- # Boyutlandırma
74
- height, width = img.shape[:2]
75
- if width > MAX_WIDTH or height > MAX_HEIGHT:
76
- img = cv2.resize(img, (MAX_WIDTH, MAX_HEIGHT), interpolation=cv2.INTER_AREA)
77
-
78
- # Kontrast iyileştirme
79
- lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
80
  l, a, b = cv2.split(lab)
81
- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
82
- limg = cv2.merge([clahe.apply(l), a, b])
83
- enhanced = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
84
-
85
- return Image.fromarray(cv2.cvtColor(enhanced, cv2.COLOR_BGR2RGB))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  def detect_chart_elements(image):
88
- inputs = detection_processor(images=image, return_tensors="pt")
 
 
 
 
89
  with torch.no_grad():
90
  outputs = detection_model(**inputs)
91
 
92
- target_sizes = torch.tensor([image.size[::-1]])
93
  results = detection_processor.post_process_object_detection(
94
  outputs,
95
- target_sizes=target_sizes,
96
- threshold=0.7
97
  )[0]
98
 
99
  elements = {
@@ -101,81 +132,115 @@ def detect_chart_elements(image):
101
  'trendlines': [],
102
  'patterns': [],
103
  'candlesticks': [],
 
104
  }
105
 
106
  draw = ImageDraw.Draw(image)
 
 
107
  for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
108
  box = [round(i, 2) for i in box.tolist()]
109
  label_name = detection_model.config.id2label[label.item()]
110
-
111
- # Çizim işlemleri
112
- draw.rectangle(box, outline="red", width=2)
113
- draw.text((box[0], box[1]), f"{label_name} ({round(score.item(), 2)})", fill="red")
114
-
115
- # Element kategorizasyonu
116
- if "support" in label_name.lower() or "resistance" in label_name.lower():
117
- elements['support_resistance'].append(label_name)
118
- elif "trendline" in label_name.lower():
119
- elements['trendlines'].append(label_name)
120
- elif "pattern" in label_name.lower():
121
- elements['patterns'].append(label_name)
122
- elif "candlestick" in label_name.lower():
123
- elements['candlesticks'].append(label_name)
124
 
125
- return image, elements
126
-
127
- def generate_llm_response(elements, question):
128
- prompt = SYSTEM_PROMPT.format(
129
- support_resistance=", ".join(elements['support_resistance']) or "None detected",
130
- trendlines=", ".join(elements['trendlines']) or "None detected",
131
- patterns=", ".join(elements['patterns']) or "None detected",
132
- candlesticks=", ".join(elements['candlesticks']) or "None detected",
133
- question=question
134
- )
 
 
 
 
 
135
 
136
- response = llm_client.text_generation(
137
- prompt,
138
- max_new_tokens=1024,
139
- temperature=0.2,
140
- top_p=0.9,
141
- do_sample=True
142
- )
 
143
 
144
- return response.split("<|assistant|>")[-1].strip()
 
 
 
 
 
 
 
 
 
 
145
 
146
- # Gradio Arayüzü
147
  def respond(message, history, image):
148
  if image is None:
149
- return "Please upload a chart image first."
150
 
151
  try:
152
- processed_img = preprocess_image(image)
153
  annotated_img, elements = detect_chart_elements(processed_img)
154
- analysis = generate_llm_response(elements, message)
155
- img_base64 = image_to_base64(annotated_img)
156
- img_html = f'<img src="data:image/png;base64,{img_base64}" style="max-width: 800px; margin-bottom: 20px;">'
157
- return f"{img_html}\n{analysis}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  except Exception as e:
159
- return f"Error processing request: {str(e)}"
160
 
161
- # Interface
162
  demo = gr.ChatInterface(
163
  fn=respond,
164
- additional_inputs=[gr.Image(label="Upload Chart", type="pil")],
165
  chatbot=gr.Chatbot(
 
166
  show_copy_button=True,
167
- layout="panel",
168
  bubble_full_width=False,
169
  sanitize_html=False
170
  ),
171
- title="Crypto Trading Assistant Pro",
 
 
 
 
 
 
 
 
 
172
  theme="Nymbo/Nymbo_Theme",
173
  textbox=gr.Textbox(
174
  label="Ask Technical Questions",
175
- placeholder="Upload chart image and ask analysis questions...",
176
  container=False
177
  )
178
  )
179
 
180
  if __name__ == "__main__":
181
- demo.launch()
 
1
  import gradio as gr
2
  import cv2
3
  import numpy as np
 
 
 
 
4
  from PIL import Image, ImageDraw
5
  import warnings
6
  import io
7
  import torch
8
  import base64
9
  import os
10
+ import matplotlib.pyplot as plt
11
+ from scipy import stats
12
+ from sklearn.cluster import DBSCAN
13
+ from transformers import (
14
+ AutoModelForObjectDetection,
15
+ DetrImageProcessor,
16
+ pipeline
17
+ )
18
  from huggingface_hub import InferenceClient
19
 
 
 
20
  warnings.filterwarnings("ignore")
21
 
22
  # Constants
23
+ MAX_SIZE = 1024
24
+ CLAHE_CLIP = 3.0
25
+ CANNY_THRESHOLDS = (50, 200)
26
+ HOUGH_PARAMS = (50, 30, 50)
27
+ DBSCAN_EPS = 10.0
28
+ MIN_SAMPLES = 5
29
 
30
+ # CPU optimizations
31
+ os.environ["OMP_NUM_THREADS"] = str(os.cpu_count() or 8)
32
+ torch.set_num_threads(os.cpu_count() or 8)
33
 
34
+ # Model configurations
35
+ DETECTION_MODEL = "nickmuchi/yolos-small-finance"
36
+ LLM_MODEL_NAME = "meta-llama/Meta-Llama-3-70B-Instruct"
37
 
38
+ # Initialize models
39
  detection_processor = DetrImageProcessor.from_pretrained(DETECTION_MODEL)
40
  detection_model = AutoModelForObjectDetection.from_pretrained(DETECTION_MODEL)
41
+ llm_client = InferenceClient(model=LLM_MODEL_NAME, token=os.getenv("HF_TOKEN"))
42
 
43
+ # Enhanced system prompt
 
 
 
 
 
 
44
  SYSTEM_PROMPT = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>
45
+ You are a senior cryptocurrency trading analyst with 15 years experience. Analyze the following comprehensive chart data:
46
+
47
+ Technical Elements Detected:
48
+ {technical_analysis}
49
+
50
+ User Query: {question}
51
+
52
+ Provide detailed professional analysis covering:
53
+ 1. Price Action Analysis (Trend Strength, Momentum)
54
+ 2. Key Support/Resistance Zones (Cluster Analysis)
55
+ 3. Volume-Weighted Price Levels
56
+ 4. Pattern Recognition (Continuation/Reversal)
57
+ 5. Fibonacci Retracement Levels (if applicable)
58
+ 6. Market Structure Analysis
59
+ 7. Risk/Reward Ratios
60
+ 8. Optimal Trade Entry/Exit Strategies
61
+
62
+ 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|>
63
  """
64
 
65
+ def adaptive_resize(image):
66
+ height, width = image.size
67
+ scale = MAX_SIZE / max(height, width)
68
+ return image.resize((int(width*scale), int(height*scale)), Image.LANCZOS)
 
69
 
70
+ def enhance_contrast(img):
71
+ lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
 
 
 
 
 
 
 
 
 
72
  l, a, b = cv2.split(lab)
73
+ clahe = cv2.createCLAHE(clipLimit=CLAHE_CLIP, tileGridSize=(8,8))
74
+ limg = clahe.apply(l)
75
+ merged = cv2.merge([limg, a, b])
76
+ return cv2.cvtColor(merged, cv2.COLOR_LAB2RGB)
77
+
78
+ def detect_lines(image):
79
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
80
+ edges = cv2.Canny(gray, *CANNY_THRESHOLDS)
81
+ lines = cv2.HoughLinesP(edges, 1, np.pi/180, *HOUGH_PARAMS)
82
+ return lines
83
+
84
+ def cluster_lines(lines):
85
+ if lines is None:
86
+ return []
87
+ points = lines.reshape(-1, 2)
88
+ clustering = DBSCAN(eps=DBSCAN_EPS, min_samples=MIN_SAMPLES).fit(points)
89
+ return clustering.labels_
90
+
91
+ def calculate_slope(line):
92
+ x1, y1, x2, y2 = line
93
+ return (y2 - y1) / (x2 - x1) if (x2 - x1) != 0 else np.inf
94
+
95
+ def detect_key_levels(image):
96
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
97
+ hist = cv2.calcHist([gray], [0], None, [256], [0,256])
98
+ peaks, _ = find_peaks(hist.flatten(), distance=10, prominence=50)
99
+ return [p for p in peaks if 10 < p < 240]
100
+
101
+ def analyze_volume_profile(image):
102
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
103
+ return cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
104
+
105
+ def detect_candlesticks(image):
106
+ edges = cv2.Canny(image, 50, 150)
107
+ contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
108
+ candles = []
109
+ for cnt in contours:
110
+ x,y,w,h = cv2.boundingRect(cnt)
111
+ if 5 < w < 50 and 10 < h < 200:
112
+ candles.append((x,y,w,h))
113
+ return candles
114
 
115
  def detect_chart_elements(image):
116
+ image_np = np.array(image)
117
+ enhanced = enhance_contrast(image_np)
118
+
119
+ # Deep Learning Detection
120
+ inputs = detection_processor(images=Image.fromarray(enhanced), return_tensors="pt")
121
  with torch.no_grad():
122
  outputs = detection_model(**inputs)
123
 
 
124
  results = detection_processor.post_process_object_detection(
125
  outputs,
126
+ target_sizes=torch.tensor([image.size[::-1]]),
127
+ threshold=0.85
128
  )[0]
129
 
130
  elements = {
 
132
  'trendlines': [],
133
  'patterns': [],
134
  'candlesticks': [],
135
+ 'indicators': []
136
  }
137
 
138
  draw = ImageDraw.Draw(image)
139
+
140
+ # Process DL detections
141
  for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
142
  box = [round(i, 2) for i in box.tolist()]
143
  label_name = detection_model.config.id2label[label.item()]
144
+ elements['patterns' if 'pattern' in label_name else 'indicators'].append(label_name)
145
+ draw.rectangle(box, outline="#FF0000", width=3)
146
+ draw.text((box[0], box[1]), f"{label_name} ({score:.2f})", fill="#FF0000")
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ # Traditional CV Detection
149
+ lines = detect_lines(enhanced)
150
+ if lines is not None:
151
+ clusters = cluster_lines(lines)
152
+ for i, line in enumerate(lines):
153
+ x1, y1, x2, y2 = line[0]
154
+ slope = calculate_slope(line[0])
155
+ length = np.sqrt((x2-x1)**2 + (y2-y1)**2)
156
+
157
+ if abs(slope) < 0.1 and length > 100:
158
+ elements['support_resistance'].append(f"Key Level at y={y1}")
159
+ draw.line((x1, y1, x2, y2), fill="#00FF00", width=3)
160
+ elif 0.1 < abs(slope) < 5:
161
+ elements['trendlines'].append(f"Trendline ({'Up' if slope < 0 else 'Down'})")
162
+ draw.line((x1, y1, x2, y2), fill="#0000FF", width=3)
163
 
164
+ # Volume Profile Analysis
165
+ volume_profile = analyze_volume_profile(enhanced)
166
+ contours, _ = cv2.findContours(volume_profile, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
167
+ for cnt in contours:
168
+ if cv2.contourArea(cnt) > 1000:
169
+ x,y,w,h = cv2.boundingRect(cnt)
170
+ elements['support_resistance'].append(f"Volume Cluster at {y+h//2}")
171
+ draw.rectangle([x,y,x+w,y+h], outline="#FFA500", width=2)
172
 
173
+ return image, elements
174
+
175
+ def generate_technical_report(elements):
176
+ report = []
177
+ if elements['support_resistance']:
178
+ report.append("**Key Levels**: " + ", ".join(elements['support_resistance'][:5]))
179
+ if elements['trendlines']:
180
+ report.append("**Trend Analysis**: " + ", ".join(elements['trendlines']))
181
+ if elements['patterns']:
182
+ report.append("**Chart Patterns**: " + ", ".join(elements['patterns']))
183
+ return "\n".join(report)
184
 
 
185
  def respond(message, history, image):
186
  if image is None:
187
+ return "Please upload a cryptocurrency chart for analysis."
188
 
189
  try:
190
+ processed_img = adaptive_resize(image)
191
  annotated_img, elements = detect_chart_elements(processed_img)
192
+ tech_report = generate_technical_report(elements)
193
+
194
+ full_prompt = SYSTEM_PROMPT.format(
195
+ technical_analysis=tech_report,
196
+ question=message
197
+ )
198
+
199
+ response = llm_client.text_generation(
200
+ full_prompt,
201
+ max_new_tokens=1500,
202
+ temperature=0.1,
203
+ repetition_penalty=1.1,
204
+ seed=42
205
+ )
206
+
207
+ img_base64 = base64.b64encode(annotated_img.tobytes()).decode('utf-8')
208
+ img_html = f'<div style="border: 2px solid #4CAF50; padding: 10px; margin-bottom: 20px;">' \
209
+ f'<img src="data:image/png;base64,{img_base64}" style="max-width: 100%;">' \
210
+ f'</div>'
211
+
212
+ return f"{img_html}\n{response.split('<|assistant|>')[-1].strip()}"
213
+
214
  except Exception as e:
215
+ return f"⚠️ Advanced Analysis Error: {str(e)}"
216
 
 
217
  demo = gr.ChatInterface(
218
  fn=respond,
219
+ additional_inputs=[gr.Image(label="Upload Crypto Chart", type="pil")],
220
  chatbot=gr.Chatbot(
221
+ avatar_images=["🤖", "📊"],
222
  show_copy_button=True,
223
+ layout="bubble",
224
  bubble_full_width=False,
225
  sanitize_html=False
226
  ),
227
+ title="CryptoQuantum Analyst Pro",
228
+ description="""<div style="text-align: center; border-bottom: 3px solid #4CAF50; padding: 20px;">
229
+ <h1>🪙 CryptoQuantum Analyst Pro</h1>
230
+ <p>Advanced AI-powered Cryptocurrency Technical Analysis System</p>
231
+ <div style="display: flex; justify-content: center; gap: 15px; margin-top: 10px;">
232
+ <div style="background: #4CAF5050; padding: 10px; border-radius: 5px;">📈 Multi-Timeframe Analysis</div>
233
+ <div style="background: #4CAF5050; padding: 10px; border-radius: 5px;">🔍 Deep Pattern Recognition</div>
234
+ <div style="background: #4CAF5050; padding: 10px; border-radius: 5px;">🤖 Neural Market Forecasting</div>
235
+ </div>
236
+ </div>""",
237
  theme="Nymbo/Nymbo_Theme",
238
  textbox=gr.Textbox(
239
  label="Ask Technical Questions",
240
+ placeholder="Enter your crypto analysis questions...",
241
  container=False
242
  )
243
  )
244
 
245
  if __name__ == "__main__":
246
+ demo.launch()