mobenta commited on
Commit
9c180e1
·
verified ·
1 Parent(s): 0663d5a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -20
app.py CHANGED
@@ -1,21 +1,23 @@
1
  import torch
2
- import gradio as gr
3
- from transformers import AutoProcessor, AutoModelForPreTraining
4
  import matplotlib.pyplot as plt
5
  import mplfinance as mpf
6
- import yfinance as yf
7
  from PIL import Image, ImageDraw, ImageFont
 
8
  import datetime
9
- import tempfile
10
  import logging
 
 
 
11
 
12
  # Configure logging
13
  logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
14
 
15
- # Load the model and processor
16
  processor = AutoProcessor.from_pretrained("mobenta/chart_analysis")
17
  model = AutoModelForPreTraining.from_pretrained("mobenta/chart_analysis")
18
 
 
19
  def predict(image, input_text):
20
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
  model.to(device)
@@ -23,7 +25,7 @@ def predict(image, input_text):
23
  image = image.convert("RGB")
24
  inputs = processor(text=input_text, images=image, return_tensors="pt")
25
  inputs = {k: v.to(device) for k, v in inputs.items()}
26
-
27
  prompt_length = inputs['input_ids'].shape[1]
28
  generate_ids = model.generate(**inputs, max_new_tokens=512)
29
  output_text = processor.batch_decode(generate_ids[:, prompt_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
@@ -50,10 +52,10 @@ def create_stock_chart(data, ticker, filename='chart.png', timeframe='1d', indic
50
  try:
51
  logging.debug(f"Creating chart for {ticker} with timeframe {timeframe} and saving to {filename}")
52
  title = f"{ticker.upper()} Price Data (Timeframe: {timeframe})"
53
-
54
  plt.rcParams["axes.titlesize"] = 10
55
  my_style = mpf.make_mpf_style(base_mpf_style='charles')
56
-
57
  # Calculate indicators if selected
58
  addplot = []
59
  if indicators:
@@ -93,7 +95,7 @@ def create_stock_chart(data, ticker, filename='chart.png', timeframe='1d', indic
93
 
94
  fig, axlist = mpf.plot(data, type='candle', style=my_style, volume=True, addplot=addplot, returnfig=True)
95
  fig.suptitle(title, y=0.98)
96
-
97
  # Save chart image
98
  fig.savefig(filename, dpi=300)
99
  plt.close(fig)
@@ -117,7 +119,7 @@ def create_stock_chart(data, ticker, filename='chart.png', timeframe='1d', indic
117
  metrics["SMA 50"] = f"${data['Close'].rolling(window=50).mean().iloc[-1]:,.2f}"
118
  if 'SMA200' in indicators:
119
  metrics["SMA 200"] = f"${data['Close'].rolling(window=200).mean().iloc[-1]:,.2f}"
120
-
121
  # Draw metrics on the image
122
  y_text = image.height - 50 # Starting y position for text
123
  for key, value in metrics.items():
@@ -130,23 +132,47 @@ def create_stock_chart(data, ticker, filename='chart.png', timeframe='1d', indic
130
  resized_image = image.resize(new_size, Image.LANCZOS)
131
  resized_image.save(filename)
132
 
133
- logging.debug(f"Resized image saved to {filename}")
134
- return filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  except Exception as e:
136
- logging.error(f"Error creating stock chart: {e}")
137
  raise
138
 
139
  def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, query, analysis_type, interval, indicators):
140
  try:
141
- chart_paths = []
 
142
  tickers = [ticker1, ticker2, ticker3, ticker4]
 
143
 
144
- for ticker in tickers:
145
- if ticker.strip():
146
- data = fetch_stock_data(ticker, start_date, end_date, interval)
147
- chart_path = f"{ticker}_chart.png"
148
- create_stock_chart(data, ticker, filename=chart_path, timeframe=interval, indicators=indicators)
149
- chart_paths.append(chart_path)
 
150
 
151
  if analysis_type == 'Comparative Analysis' and len(chart_paths) > 1:
152
  with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_combined_chart:
@@ -155,6 +181,7 @@ def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, q
155
  insights = predict(Image.open(combined_chart_path), query)
156
  return insights, combined_chart_path
157
 
 
158
  if chart_paths:
159
  insights = predict(Image.open(chart_paths[0]), query)
160
  return insights, chart_paths[0]
 
1
  import torch
2
+ import yfinance as yf
 
3
  import matplotlib.pyplot as plt
4
  import mplfinance as mpf
 
5
  from PIL import Image, ImageDraw, ImageFont
6
+ import gradio as gr
7
  import datetime
 
8
  import logging
9
+ from transformers import AutoProcessor, AutoModelForPreTraining
10
+ import tempfile
11
+ import os
12
 
13
  # Configure logging
14
  logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
15
 
16
+ # Load the ChartGemma model and processor
17
  processor = AutoProcessor.from_pretrained("mobenta/chart_analysis")
18
  model = AutoModelForPreTraining.from_pretrained("mobenta/chart_analysis")
19
 
20
+ @spaces.GPU
21
  def predict(image, input_text):
22
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
  model.to(device)
 
25
  image = image.convert("RGB")
26
  inputs = processor(text=input_text, images=image, return_tensors="pt")
27
  inputs = {k: v.to(device) for k, v in inputs.items()}
28
+
29
  prompt_length = inputs['input_ids'].shape[1]
30
  generate_ids = model.generate(**inputs, max_new_tokens=512)
31
  output_text = processor.batch_decode(generate_ids[:, prompt_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
 
52
  try:
53
  logging.debug(f"Creating chart for {ticker} with timeframe {timeframe} and saving to {filename}")
54
  title = f"{ticker.upper()} Price Data (Timeframe: {timeframe})"
55
+
56
  plt.rcParams["axes.titlesize"] = 10
57
  my_style = mpf.make_mpf_style(base_mpf_style='charles')
58
+
59
  # Calculate indicators if selected
60
  addplot = []
61
  if indicators:
 
95
 
96
  fig, axlist = mpf.plot(data, type='candle', style=my_style, volume=True, addplot=addplot, returnfig=True)
97
  fig.suptitle(title, y=0.98)
98
+
99
  # Save chart image
100
  fig.savefig(filename, dpi=300)
101
  plt.close(fig)
 
119
  metrics["SMA 50"] = f"${data['Close'].rolling(window=50).mean().iloc[-1]:,.2f}"
120
  if 'SMA200' in indicators:
121
  metrics["SMA 200"] = f"${data['Close'].rolling(window=200).mean().iloc[-1]:,.2f}"
122
+
123
  # Draw metrics on the image
124
  y_text = image.height - 50 # Starting y position for text
125
  for key, value in metrics.items():
 
132
  resized_image = image.resize(new_size, Image.LANCZOS)
133
  resized_image.save(filename)
134
 
135
+ logging.debug(f"Resized image with timeframe {timeframe} and ticker {ticker} saved to {filename}")
136
+ except Exception as e:
137
+ logging.error(f"Error creating or resizing chart: {e}")
138
+ raise
139
+
140
+ def combine_images(image_paths, output_path='combined_chart.png'):
141
+ try:
142
+ logging.debug(f"Combining images {image_paths} into {output_path}")
143
+ images = [Image.open(path) for path in image_paths]
144
+
145
+ # Calculate total width and max height for combined image
146
+ total_width = sum(img.width for img in images)
147
+ max_height = max(img.height for img in images)
148
+
149
+ combined_image = Image.new('RGB', (total_width, max_height))
150
+ x_offset = 0
151
+ for img in images:
152
+ combined_image.paste(img, (x_offset, 0))
153
+ x_offset += img.width
154
+
155
+ combined_image.save(output_path)
156
+ logging.debug(f"Combined image saved to {output_path}")
157
+ return output_path
158
  except Exception as e:
159
+ logging.error(f"Error combining images: {e}")
160
  raise
161
 
162
  def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, query, analysis_type, interval, indicators):
163
  try:
164
+ logging.debug(f"Starting gradio_interface with tickers: {ticker1}, {ticker2}, {ticker3}, {ticker4}, start_date: {start_date}, end_date: {end_date}, query: {query}, analysis_type: {analysis_type}, interval: {interval}")
165
+
166
  tickers = [ticker1, ticker2, ticker3, ticker4]
167
+ chart_paths = []
168
 
169
+ for i, ticker in enumerate(tickers):
170
+ if ticker:
171
+ data = fetch_stock_data(ticker, start=start_date, end=end_date, interval=interval)
172
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_chart:
173
+ chart_path = temp_chart.name
174
+ create_stock_chart(data, ticker, chart_path, timeframe=interval, indicators=indicators)
175
+ chart_paths.append(chart_path)
176
 
177
  if analysis_type == 'Comparative Analysis' and len(chart_paths) > 1:
178
  with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_combined_chart:
 
181
  insights = predict(Image.open(combined_chart_path), query)
182
  return insights, combined_chart_path
183
 
184
+ # No comparative analysis, just return the single chart
185
  if chart_paths:
186
  insights = predict(Image.open(chart_paths[0]), query)
187
  return insights, chart_paths[0]