cryogenic22 commited on
Commit
0948d48
·
verified ·
1 Parent(s): 42c48e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -79
app.py CHANGED
@@ -3,69 +3,30 @@ import base64
3
  from datetime import datetime
4
  import json
5
  import os
6
- from openai import OpenAI
7
- import requests
8
  from PIL import Image
9
  import io
10
  import yaml
11
 
12
- def load_openai_key():
13
- """Load OpenAI API key from HuggingFace secrets"""
14
  try:
15
- # Try to get from HuggingFace secrets via environment variable
16
- api_key = os.getenv('OPENAI_API_KEY')
17
-
18
  if not api_key:
19
- st.error("OpenAI API key not found in HuggingFace secrets. Please ensure the secret is set as OPENAI_API_KEY_HF in your HuggingFace space.")
20
  return None
21
-
22
  return api_key
23
  except Exception as e:
24
- st.error(f"Error loading OpenAI API key from HuggingFace secrets: {str(e)}")
25
  return None
26
 
27
- def initialize_openai_client():
28
- """Initialize OpenAI client with API key"""
29
- api_key = load_openai_key()
30
  if api_key:
31
- return OpenAI(api_key=api_key)
32
  return None
33
 
34
- def detect_chart_type(client, image_data):
35
- """Detect chart type using OpenAI's GPT-4 vision model"""
36
- try:
37
- encoded_image = base64.b64encode(image_data).decode('utf-8')
38
-
39
- messages = [
40
- {
41
- "role": "user",
42
- "content": [
43
- {
44
- "type": "text",
45
- "text": "What type of financial chart is this? Choose from: Candlestick, Line, OHLC, Area, or Other. Just respond with one word."
46
- },
47
- {
48
- "type": "image_url",
49
- "image_url": {
50
- "url": f"data:image/jpeg;base64,{encoded_image}"
51
- }
52
- }
53
- ]
54
- }
55
- ]
56
-
57
- response = client.chat.completions.create(
58
- model="gpt-4",
59
- messages=messages,
60
- max_tokens=50
61
- )
62
-
63
- chart_type = response.choices[0].message.content.strip()
64
- return chart_type
65
- except Exception as e:
66
- st.error(f"Error in chart type detection: {str(e)}")
67
- return "Other"
68
-
69
  def create_prompt_template(patterns, indicators):
70
  """Creates a structured prompt for the LLM based on the chart and analysis needs"""
71
  prompt = """You are an expert financial analyst. Please analyze this financial chart (chart type will be detected automatically) and provide insights in the following structured format:
@@ -106,8 +67,41 @@ def create_prompt_template(patterns, indicators):
106
  indicators=', '.join(indicators) if indicators else 'visible indicators'
107
  )
108
 
109
- def analyze_chart_with_openai(client, image_data, prompt, chart_type=None):
110
- """Analyze chart using OpenAI's GPT-4 model"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  try:
112
  encoded_image = base64.b64encode(image_data).decode('utf-8')
113
 
@@ -116,8 +110,10 @@ def analyze_chart_with_openai(client, image_data, prompt, chart_type=None):
116
  chart_type = detect_chart_type(client, image_data)
117
  st.info(f"Detected chart type: {chart_type}")
118
 
119
- messages = [
120
- {
 
 
121
  "role": "user",
122
  "content": [
123
  {
@@ -125,24 +121,20 @@ def analyze_chart_with_openai(client, image_data, prompt, chart_type=None):
125
  "text": prompt.format(chart_type=chart_type)
126
  },
127
  {
128
- "type": "image_url",
129
- "image_url": {
130
- "url": f"data:image/jpeg;base64,{encoded_image}"
 
 
131
  }
132
  }
133
  ]
134
- }
135
- ]
136
-
137
- response = client.chat.completions.create(
138
- model="gpt-4o",
139
- messages=messages,
140
- max_tokens=1000
141
  )
142
 
143
- return response.choices[0].message.content, chart_type
144
  except Exception as e:
145
- st.error(f"Error in OpenAI analysis: {str(e)}")
146
  return None, None
147
 
148
  def save_chat_history(chat_history, filename=None):
@@ -172,10 +164,10 @@ def main():
172
  initial_sidebar_state="expanded"
173
  )
174
 
175
- # Initialize OpenAI client
176
- client = initialize_openai_client()
177
  if not client:
178
- st.error("Failed to initialize OpenAI client. Please check your API key configuration.")
179
  return
180
 
181
  # Initialize session state for chat history
@@ -200,7 +192,6 @@ def main():
200
  elif upload_option == "Take Screenshot":
201
  if st.button("Take Screenshot", key="screenshot"):
202
  st.info("Feature coming soon! For now, please use the Upload Image option.")
203
- # Future screenshot implementation will go here
204
  screenshot_taken = False
205
 
206
  # Analysis Options
@@ -217,10 +208,6 @@ def main():
217
  "Volume", "Stochastic", "ADX"]
218
  )
219
 
220
- # Initialize or get chart type from session state
221
- if 'detected_chart_type' not in st.session_state:
222
- st.session_state.detected_chart_type = None
223
-
224
  # Main content area
225
  st.title("📈 Stock Chart Analysis Assistant")
226
 
@@ -237,7 +224,6 @@ def main():
237
 
238
  if st.button("Analyze"):
239
  if upload_option == "Ask Question" and user_question:
240
- # Handle question-based analysis here
241
  st.info("Question-based analysis feature coming soon!")
242
  elif uploaded_file is None and not screenshot_taken:
243
  st.warning("Please upload an image or take a screenshot first.")
@@ -248,20 +234,17 @@ def main():
248
 
249
  if uploaded_file:
250
  # Process image and get analysis
251
- analysis_result, detected_chart_type = analyze_chart_with_openai(
252
  client,
253
  uploaded_file.getvalue(),
254
  prompt
255
  )
256
 
257
- # Store the detected chart type in session state
258
- st.session_state.detected_chart_type = detected_chart_type
259
-
260
  if analysis_result:
261
  # Add to chat history
262
  st.session_state.chat_history.append({
263
  'timestamp': datetime.now().isoformat(),
264
- 'chart_type': detected_chart_type,
265
  'analysis': analysis_result
266
  })
267
 
 
3
  from datetime import datetime
4
  import json
5
  import os
6
+ from anthropic import Anthropic
 
7
  from PIL import Image
8
  import io
9
  import yaml
10
 
11
+ def load_anthropic_key():
12
+ """Load Anthropic API key from environment variables"""
13
  try:
14
+ api_key = os.getenv('ANTHROPIC_API_KEY')
 
 
15
  if not api_key:
16
+ st.error("Anthropic API key not found. Please set ANTHROPIC_API_KEY in your environment variables.")
17
  return None
 
18
  return api_key
19
  except Exception as e:
20
+ st.error(f"Error loading Anthropic API key: {str(e)}")
21
  return None
22
 
23
+ def initialize_anthropic_client():
24
+ """Initialize Anthropic client with API key"""
25
+ api_key = load_anthropic_key()
26
  if api_key:
27
+ return Anthropic(api_key=api_key)
28
  return None
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def create_prompt_template(patterns, indicators):
31
  """Creates a structured prompt for the LLM based on the chart and analysis needs"""
32
  prompt = """You are an expert financial analyst. Please analyze this financial chart (chart type will be detected automatically) and provide insights in the following structured format:
 
67
  indicators=', '.join(indicators) if indicators else 'visible indicators'
68
  )
69
 
70
+ def detect_chart_type(client, image_data):
71
+ """Detect chart type using Claude Vision"""
72
+ try:
73
+ encoded_image = base64.b64encode(image_data).decode('utf-8')
74
+
75
+ message = client.messages.create(
76
+ model="claude-3-opus-20240229",
77
+ max_tokens=50,
78
+ messages=[{
79
+ "role": "user",
80
+ "content": [
81
+ {
82
+ "type": "text",
83
+ "text": "What type of financial chart is this? Choose from: Candlestick, Line, OHLC, Area, or Other. Just respond with one word."
84
+ },
85
+ {
86
+ "type": "image",
87
+ "source": {
88
+ "type": "base64",
89
+ "media_type": "image/jpeg",
90
+ "data": encoded_image
91
+ }
92
+ }
93
+ ]
94
+ }]
95
+ )
96
+
97
+ chart_type = message.content[0].text.strip()
98
+ return chart_type
99
+ except Exception as e:
100
+ st.error(f"Error in chart type detection: {str(e)}")
101
+ return "Other"
102
+
103
+ def analyze_chart_with_claude(client, image_data, prompt, chart_type=None):
104
+ """Analyze chart using Claude Vision"""
105
  try:
106
  encoded_image = base64.b64encode(image_data).decode('utf-8')
107
 
 
110
  chart_type = detect_chart_type(client, image_data)
111
  st.info(f"Detected chart type: {chart_type}")
112
 
113
+ message = client.messages.create(
114
+ model="claude-3-opus-20240229",
115
+ max_tokens=1000,
116
+ messages=[{
117
  "role": "user",
118
  "content": [
119
  {
 
121
  "text": prompt.format(chart_type=chart_type)
122
  },
123
  {
124
+ "type": "image",
125
+ "source": {
126
+ "type": "base64",
127
+ "media_type": "image/jpeg",
128
+ "data": encoded_image
129
  }
130
  }
131
  ]
132
+ }]
 
 
 
 
 
 
133
  )
134
 
135
+ return message.content[0].text, chart_type
136
  except Exception as e:
137
+ st.error(f"Error in Claude analysis: {str(e)}")
138
  return None, None
139
 
140
  def save_chat_history(chat_history, filename=None):
 
164
  initial_sidebar_state="expanded"
165
  )
166
 
167
+ # Initialize Anthropic client
168
+ client = initialize_anthropic_client()
169
  if not client:
170
+ st.error("Failed to initialize Anthropic client. Please check your API key configuration.")
171
  return
172
 
173
  # Initialize session state for chat history
 
192
  elif upload_option == "Take Screenshot":
193
  if st.button("Take Screenshot", key="screenshot"):
194
  st.info("Feature coming soon! For now, please use the Upload Image option.")
 
195
  screenshot_taken = False
196
 
197
  # Analysis Options
 
208
  "Volume", "Stochastic", "ADX"]
209
  )
210
 
 
 
 
 
211
  # Main content area
212
  st.title("📈 Stock Chart Analysis Assistant")
213
 
 
224
 
225
  if st.button("Analyze"):
226
  if upload_option == "Ask Question" and user_question:
 
227
  st.info("Question-based analysis feature coming soon!")
228
  elif uploaded_file is None and not screenshot_taken:
229
  st.warning("Please upload an image or take a screenshot first.")
 
234
 
235
  if uploaded_file:
236
  # Process image and get analysis
237
+ analysis_result, chart_type = analyze_chart_with_claude(
238
  client,
239
  uploaded_file.getvalue(),
240
  prompt
241
  )
242
 
 
 
 
243
  if analysis_result:
244
  # Add to chat history
245
  st.session_state.chat_history.append({
246
  'timestamp': datetime.now().isoformat(),
247
+ 'chart_type': chart_type,
248
  'analysis': analysis_result
249
  })
250