ir12345 commited on
Commit
9d27ef5
·
verified ·
1 Parent(s): 78358df

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ import cv2
3
+ import streamlit as st
4
+ import os
5
+ import numpy as np
6
+
7
+ st.set_page_config(layout="wide")
8
+ model = None
9
+ user_inputs = {}
10
+
11
+ with st.sidebar:
12
+ st.title("Calculate Product Costs from Images")
13
+ st.write("Simplify pricing with AI-powered image recognition and price summation.")
14
+ st.text("1.Upload Model (YOLO or etc.)\n2.Set The price (Default is 0)\n3.Upload An Image\n(Optional) 4.Set The Model Confidence")
15
+
16
+ model_file = st.file_uploader("Upload your model file (.pt)", type=["pt"])
17
+
18
+ if model_file is not None:
19
+ # st.success(f"Model file '{model_file.name}' uploaded successfully!")
20
+ temp_model_path = os.path.join("./", model_file.name)
21
+ with open(temp_model_path, "wb") as f:
22
+ f.write(model_file.getbuffer())
23
+ st.success(f"Model file '{model_file.name}' uploaded and saved successfully!")
24
+
25
+ try:
26
+ model = YOLO(temp_model_path)
27
+ st.success("Model loaded successfully!")
28
+ class_names = model.names
29
+
30
+ st.write("Enter The Prices:")
31
+ for idx, name in class_names.items():
32
+ user_input = st.text_input(f"Class {idx}: {name}", key=f"class_{idx}")
33
+ user_inputs[idx] = user_input
34
+
35
+ if 'collected_list' not in st.session_state:
36
+ st.session_state.collected_list = []
37
+
38
+ if st.button("Submit"):
39
+ st.write("Collected Inputs:")
40
+ st.session_state.collected_list = []
41
+ for idx in range(len(class_names)):
42
+ if user_inputs[idx] == "":
43
+ user_inputs[idx] = 0
44
+ elif not user_inputs[idx].isdigit():
45
+ user_inputs[idx] = 0
46
+ st.session_state.collected_list.append(int(user_inputs[idx]))
47
+ st.write(st.session_state.collected_list)
48
+ except Exception as e:
49
+ st.error(f"Error loading model: {e}")
50
+ else:
51
+ st.warning("Please upload a model file that ends with .pt")
52
+
53
+ if model != None:
54
+
55
+ st.subheader("Image Display")
56
+ image_placeholder = st.empty()
57
+
58
+ uploaded_image = st.file_uploader("Upload an image to display", type=["png", "jpg", "jpeg"], key="image")
59
+ conf_str = st.text_input(f"Model Confidence (Default is 0.5)")
60
+ if uploaded_image is not None:
61
+ file_bytes = np.asarray(bytearray(uploaded_image.read()), dtype=np.uint8)
62
+ img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
63
+
64
+ if st.button("Predict The Image"):
65
+ if model is not None and uploaded_image is not None:
66
+ if st.session_state.collected_list != []:
67
+ try:
68
+ conf_ = float(conf_str)
69
+ except Exception as e:
70
+ if not isinstance(conf_str, float):
71
+ conf_ = 0.5
72
+
73
+ results = model.predict(source=img, conf=conf_)
74
+ if 'sum_price' not in st.session_state:
75
+ st.session_state.sum_price = 0
76
+
77
+ for result in results:
78
+ for box in result.boxes:
79
+ # Get box coordinates
80
+ x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
81
+ cls = int(box.cls[0])
82
+ conf = box.conf[0]
83
+ st.write(f"{result.names[int(box.cls[0])]} : {st.session_state.collected_list[int(box.cls[0])]}")
84
+ st.session_state.sum_price += st.session_state.collected_list[int(box.cls[0])]
85
+ label = f"{result.names[int(box.cls[0])]}: {conf:.2f}"
86
+ cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
87
+ cv2.putText(img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
88
+
89
+ st.subheader(f"Sum Price: {st.session_state.sum_price}")
90
+ st.image(img, channels="BGR", caption="Uploaded Image")
91
+ st.session_state.sum_price = 0
92
+ else:
93
+ st.warning("Please Submit The Price")
94
+ else:
95
+ st.warning("Please Upload an Image")
96
+