Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
import numpy as np
|
| 3 |
-
import streamlit as st
|
| 4 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
from sklearn.preprocessing import LabelEncoder
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def load_car_data():
|
| 9 |
try:
|
| 10 |
df = pd.read_csv('CTP_Model1.csv') # Replace with the path to your actual CSV file
|
|
@@ -47,41 +94,81 @@ def find_closest_car(df, label_encoders, make, model, year):
|
|
| 47 |
# Return the closest match details
|
| 48 |
return df.iloc[closest_match_idx]
|
| 49 |
|
| 50 |
-
# Streamlit App
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
#
|
|
|
|
| 58 |
|
| 59 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
if st.session_state.image is not None:
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
with st.spinner('Analyzing image...'):
|
| 63 |
car_classifications = classify_image(st.session_state.image)
|
| 64 |
|
| 65 |
if car_classifications:
|
| 66 |
st.write("Image classification successful.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
top_prediction = car_classifications[0]['label']
|
| 68 |
make_name, model_name = top_prediction.split(' ', 1)
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
# Get
|
| 71 |
current_year = datetime.now().year
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
# Find the closest match in the CSV based on the classification
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
| 86 |
else:
|
| 87 |
-
st.error("Could not classify the image. Please try again with a different image.")
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
| 4 |
+
import torch
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import openai
|
| 7 |
import pandas as pd
|
| 8 |
import numpy as np
|
|
|
|
| 9 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 10 |
from sklearn.preprocessing import LabelEncoder
|
| 11 |
|
| 12 |
+
# Initialize OpenAI API key
|
| 13 |
+
openai.api_key = st.secrets["GPT_TOKEN"]
|
| 14 |
+
|
| 15 |
+
# Function to classify the car image using pre-trained model
|
| 16 |
+
def classify_image(image):
|
| 17 |
+
try:
|
| 18 |
+
# Load the model and feature extractor
|
| 19 |
+
model_name = "dima806/car_models_image_detection"
|
| 20 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
| 21 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
| 22 |
+
|
| 23 |
+
# Preprocess the image
|
| 24 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
| 25 |
+
|
| 26 |
+
# Perform inference
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
outputs = model(**inputs)
|
| 29 |
+
|
| 30 |
+
# Get the predicted class
|
| 31 |
+
logits = outputs.logits
|
| 32 |
+
predicted_class_idx = logits.argmax(-1).item()
|
| 33 |
+
|
| 34 |
+
# Get the class label and score
|
| 35 |
+
predicted_class_label = model.config.id2label[predicted_class_idx]
|
| 36 |
+
score = torch.nn.functional.softmax(logits, dim=-1)[0, predicted_class_idx].item()
|
| 37 |
+
|
| 38 |
+
# Return the top prediction
|
| 39 |
+
return [{'label': predicted_class_label, 'score': score}]
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
st.error(f"Classification error: {e}")
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
# Function to get an overview of the car using OpenAI
|
| 46 |
+
def get_car_overview(brand, model, year):
|
| 47 |
+
prompt = f"Provide an overview of the following car:\nYear: {year}\nMake: {brand}\nModel: {model}\n"
|
| 48 |
+
response = openai.ChatCompletion.create(
|
| 49 |
+
model="gpt-3.5-turbo",
|
| 50 |
+
messages=[{"role": "user", "content": prompt}]
|
| 51 |
+
)
|
| 52 |
+
return response.choices[0].message['content']
|
| 53 |
+
|
| 54 |
+
# Load and preprocess the car data once (globally for the session)
|
| 55 |
def load_car_data():
|
| 56 |
try:
|
| 57 |
df = pd.read_csv('CTP_Model1.csv') # Replace with the path to your actual CSV file
|
|
|
|
| 94 |
# Return the closest match details
|
| 95 |
return df.iloc[closest_match_idx]
|
| 96 |
|
| 97 |
+
# Streamlit App
|
| 98 |
+
st.title("Auto Appraise")
|
| 99 |
+
st.write("Upload a car image or take a picture to get its brand, model, and overview!")
|
| 100 |
|
| 101 |
+
# Initialize session_state image attribute if it doesn't exist
|
| 102 |
+
if 'image' not in st.session_state:
|
| 103 |
+
st.session_state.image = None
|
| 104 |
+
|
| 105 |
+
# File uploader for image
|
| 106 |
+
uploaded_file = st.file_uploader("Choose a car image", type=["jpg", "jpeg", "png"])
|
| 107 |
|
| 108 |
+
# Camera input as an alternative (optional)
|
| 109 |
+
camera_image = st.camera_input("Or take a picture of the car")
|
| 110 |
|
| 111 |
+
# Process the image (either uploaded or from camera)
|
| 112 |
+
if uploaded_file is not None:
|
| 113 |
+
st.write("Attempting to open uploaded file...")
|
| 114 |
+
try:
|
| 115 |
+
st.session_state.image = Image.open(uploaded_file)
|
| 116 |
+
st.write("Image uploaded successfully.")
|
| 117 |
+
except Exception as e:
|
| 118 |
+
st.error(f"Error opening uploaded file: {str(e)}")
|
| 119 |
+
elif camera_image is not None:
|
| 120 |
+
st.write("Attempting to open camera image...")
|
| 121 |
+
try:
|
| 122 |
+
st.session_state.image = Image.open(camera_image)
|
| 123 |
+
st.write("Image captured successfully.")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
st.error(f"Error opening camera image: {str(e)}")
|
| 126 |
+
|
| 127 |
+
# Display the processed image
|
| 128 |
if st.session_state.image is not None:
|
| 129 |
+
st.image(st.session_state.image, caption='Processed Image', use_container_width=True)
|
| 130 |
+
|
| 131 |
+
# Classify the car image
|
| 132 |
with st.spinner('Analyzing image...'):
|
| 133 |
car_classifications = classify_image(st.session_state.image)
|
| 134 |
|
| 135 |
if car_classifications:
|
| 136 |
st.write("Image classification successful.")
|
| 137 |
+
st.subheader("Car Classification Results:")
|
| 138 |
+
for classification in car_classifications:
|
| 139 |
+
st.write(f"Model: {classification['label']}")
|
| 140 |
+
st.write(f"Confidence: {classification['score'] * 100:.2f}%")
|
| 141 |
+
|
| 142 |
+
# Separate make and model from the classification result
|
| 143 |
top_prediction = car_classifications[0]['label']
|
| 144 |
make_name, model_name = top_prediction.split(' ', 1)
|
| 145 |
+
|
| 146 |
+
st.write(f"Identified Car Make: {make_name}")
|
| 147 |
+
st.write(f"Identified Car Model: {model_name}")
|
| 148 |
|
| 149 |
+
# Get additional information using GPT-3.5-turbo
|
| 150 |
current_year = datetime.now().year
|
| 151 |
+
overview = get_car_overview(make_name, model_name, current_year)
|
| 152 |
+
st.write("Car Overview:")
|
| 153 |
+
st.write(overview)
|
| 154 |
|
| 155 |
# Find the closest match in the CSV based on the classification
|
| 156 |
+
car_data = load_car_data()
|
| 157 |
+
if car_data is not None:
|
| 158 |
+
processed_car_data, label_encoders = preprocess_car_data(car_data)
|
| 159 |
+
closest_car = find_closest_car(processed_car_data, label_encoders, make_name, model_name, current_year)
|
| 160 |
+
|
| 161 |
+
st.write(f"Closest match in database:")
|
| 162 |
+
st.write(f"Year: {closest_car['year']}")
|
| 163 |
+
st.write(f"Make: {label_encoders['make'].inverse_transform([closest_car['make']])[0]}")
|
| 164 |
+
st.write(f"Model: {label_encoders['model'].inverse_transform([closest_car['model']])[0]}")
|
| 165 |
+
st.write(f"Price: ${closest_car['price']}")
|
| 166 |
+
st.write(f"Condition: {closest_car['condition']}")
|
| 167 |
+
st.write(f"Fuel: {closest_car['fuel']}")
|
| 168 |
+
st.write(f"Transmission: {closest_car['transmission']}")
|
| 169 |
+
st.write(f"Drive: {closest_car['drive']}")
|
| 170 |
+
st.write(f"Type: {closest_car['type']}")
|
| 171 |
else:
|
| 172 |
+
st.error("Could not classify the image. Please try again with a different image.")
|
| 173 |
+
else:
|
| 174 |
+
st.write("Please upload an image or take a picture to proceed.")
|