Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import streamlit as stfrom PIL import Imageimport torchfrom torchvision import transformsfrom torchvision.models import resnet50import io# Streamlit appst.title("Stock Trend Predictor: Bullish or Bearish?")# Load pre-trained ResNet50 model@st.cache_resourcedef load_model():model = resnet50(pretrained=True)model.fc = torch.nn.Linear(model.fc.in_features, 2) # 2 classes: bullish and bearishtry:state_dict = torch.load('Kaylah072001/stock_prediction_model.h5', map_location=torch.device('cpu'))model.load_state_dict(state_dict)st.success("Model loaded successfully!")except Exception as e:st.error(f"Error loading model: {e}")model.eval()return modelmodel = load_model()# Define image transformationtransform = transforms.Compose([transforms.Resize((224, 224)),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])uploaded_file = st.file_uploader("Upload a stock graph image", type=["jpg", "jpeg", "png"])if uploaded_file is not None:try:image = Image.open(uploaded_file).convert('RGB')st.image(image, caption="Uploaded Stock Graph", use_column_width=True)# Preprocess the imageinput_tensor = transform(image).unsqueeze(0)# Make predictionwith torch.no_grad():output = model(input_tensor)probabilities = torch.nn.functional.softmax(output[0], dim=0)predicted_class = torch.argmax(probabilities).item()# Display predictionst.header("Prediction")if predicted_class == 0:sentiment = "Bearish"else:sentiment = "Bullish"confidence = probabilities[predicted_class].item() * 100st.subheader(f"{sentiment}: {confidence:.2f}%")st.progress(confidence / 100, text=f"{sentiment} Confidence")except Exception as e:st12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import streamlit as stfrom PIL import Imageimport torchfrom transformers import AutoModelForImageClassification, AutoFeatureExtractor# Streamlit appst.title("Stock Trend Predictor: Bullish or Bearish?")# Load pre-trained model from Hugging Face@st.cache_resourcedef load_model():model_name = "Kaylah072001/stock_prediction_model" # Replace with your actual model name on Hugging Facetry:model = AutoModelForImageClassification.from_pretrained(model_name)feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)st.success("Model loaded successfully!")return model, feature_extractorexcept Exception as e:st.error(f"Error loading model: {e}")return None, Nonemodel, feature_extractor = load_model()uploaded_file = st.file_uploader("Upload a stock graph image", type=["jpg", "jpeg", "png"])if uploaded_file is not None and model is not None and feature_extractor is not None:try:image = Image.open(uploaded_file).convert('RGB')st.image(image, caption="Uploaded Stock Graph", use_column_width=True)# Preprocess the imageinputs = feature_extractor(images=image, return_tensors="pt")# Make predictionwith torch.no_grad():outputs = model(**inputs)logits = outputs.logitsprobabilities = torch.nn.functional.softmax(logits[0], dim=0)predicted_class = torch.argmax(probabilities).item()# Display predictionst.header("Prediction")sentiment = "Bullish" if predicted_class == 1 else "Bearish"confidence = probabilities[predicted_class].item() * 100st.subheader(f"{sentiment}: {confidence:.2f}%")st.progress(confidence / 100, text=f"{sentiment} Confidence")except Exception as e:st.error(f"Error processing image: {e}")
app.py+15-29