Kaylah072001 commited on
Commit
2b4ccd5
·
verified ·
1 Parent(s): 18cc71d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -15
app.py CHANGED
@@ -1,49 +1,63 @@
1
  import streamlit as st
2
  from PIL import Image
3
  import torch
4
- from transformers import AutoModelForImageClassification, AutoFeatureExtractor
 
 
5
 
6
  # Streamlit app
7
  st.title("Stock Trend Predictor: Bullish or Bearish?")
8
 
9
- # Load pre-trained model from Hugging Face
10
  @st.cache_resource
11
  def load_model():
12
- model_name = "Kaylah072001/stock_prediction_model.h5" # Replace with your actual model name on Hugging Face
 
13
  try:
14
- model = AutoModelForImageClassification.from_pretrained(model_name)
15
- feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
16
  st.success("Model loaded successfully!")
17
- return model, feature_extractor
18
  except Exception as e:
19
  st.error(f"Error loading model: {e}")
20
- return None, None
 
21
 
22
- model, feature_extractor = load_model()
 
 
 
 
 
 
 
23
 
24
  uploaded_file = st.file_uploader("Upload a stock graph image", type=["jpg", "jpeg", "png"])
25
 
26
- if uploaded_file is not None and model is not None and feature_extractor is not None:
27
  try:
28
  image = Image.open(uploaded_file).convert('RGB')
29
  st.image(image, caption="Uploaded Stock Graph", use_column_width=True)
30
 
31
  # Preprocess the image
32
- inputs = feature_extractor(images=image, return_tensors="pt")
33
 
34
  # Make prediction
35
  with torch.no_grad():
36
- outputs = model(**inputs)
37
- logits = outputs.logits
38
- probabilities = torch.nn.functional.softmax(logits[0], dim=0)
39
  predicted_class = torch.argmax(probabilities).item()
40
 
41
  # Display prediction
42
  st.header("Prediction")
43
- sentiment = "Bullish" if predicted_class == 1 else "Bearish"
 
 
 
 
 
44
  confidence = probabilities[predicted_class].item() * 100
45
  st.subheader(f"{sentiment}: {confidence:.2f}%")
46
  st.progress(confidence / 100, text=f"{sentiment} Confidence")
47
 
48
  except Exception as e:
49
- st.error(f"Error processing image: {e}")
 
1
  import streamlit as st
2
  from PIL import Image
3
  import torch
4
+ from torchvision import transforms
5
+ from torchvision.models import resnet50
6
+ import io
7
 
8
  # Streamlit app
9
  st.title("Stock Trend Predictor: Bullish or Bearish?")
10
 
11
+ # Load pre-trained ResNet50 model
12
  @st.cache_resource
13
  def load_model():
14
+ model = resnet50(pretrained=True)
15
+ model.fc = torch.nn.Linear(model.fc.in_features, 2) # 2 classes: bullish and bearish
16
  try:
17
+ state_dict = torch.load('/Users/kaylahoffman/Desktop/stock_prediction_model.h5', map_location=torch.device('cpu'))
18
+ model.load_state_dict(state_dict)
19
  st.success("Model loaded successfully!")
 
20
  except Exception as e:
21
  st.error(f"Error loading model: {e}")
22
+ model.eval()
23
+ return model
24
 
25
+ model = load_model()
26
+
27
+ # Define image transformation
28
+ transform = transforms.Compose([
29
+ transforms.Resize((224, 224)),
30
+ transforms.ToTensor(),
31
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
32
+ ])
33
 
34
  uploaded_file = st.file_uploader("Upload a stock graph image", type=["jpg", "jpeg", "png"])
35
 
36
+ if uploaded_file is not None:
37
  try:
38
  image = Image.open(uploaded_file).convert('RGB')
39
  st.image(image, caption="Uploaded Stock Graph", use_column_width=True)
40
 
41
  # Preprocess the image
42
+ input_tensor = transform(image).unsqueeze(0)
43
 
44
  # Make prediction
45
  with torch.no_grad():
46
+ output = model(input_tensor)
47
+ probabilities = torch.nn.functional.softmax(output[0], dim=0)
 
48
  predicted_class = torch.argmax(probabilities).item()
49
 
50
  # Display prediction
51
  st.header("Prediction")
52
+ if predicted_class == 0:
53
+ sentiment = "Bearish"
54
+
55
+ else:
56
+ sentiment = "Bullish"
57
+
58
  confidence = probabilities[predicted_class].item() * 100
59
  st.subheader(f"{sentiment}: {confidence:.2f}%")
60
  st.progress(confidence / 100, text=f"{sentiment} Confidence")
61
 
62
  except Exception as e:
63
+ st