saurabh091 commited on
Commit
99c9f44
·
verified ·
1 Parent(s): 6df535a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -169
app.py CHANGED
@@ -1,169 +1,176 @@
1
- # Import libraries
2
- import pandas as pd
3
- from ultralytics import YOLO
4
- from flask import Flask, render_template, request, send_from_directory
5
- from werkzeug.utils import secure_filename
6
- import os
7
- import pandas as pd
8
- import shutil
9
-
10
-
11
-
12
- def clr_static():
13
- """
14
- for removing the static folder (for memoery saving in web)
15
- """
16
- dir = 'static'
17
- try:
18
- shutil.rmtree(dir)
19
- print("Cleared Static")
20
- except:
21
- pass
22
-
23
- def clr_old_upload():
24
- """
25
- for removing the old images uploaded file (for memoery saving in web)
26
- """
27
- dir = 'UPLOAD_FOLDER'
28
- try:
29
- shutil.rmtree(dir)
30
- print("Cleared UPLOAD_FOLDER")
31
- except:
32
- pass
33
-
34
-
35
- #making dir to save the generated csv file
36
- def mk_csv_folder():
37
- try:
38
- os.mkdir("static/CSV_File")
39
- print("made csv_folder")
40
- except:
41
- pass
42
-
43
- #Creating UPLOAD_FOLDER dir to save the Uploaded file
44
- def mk_uploaded_folder():
45
- try:
46
- os.mkdir("UPLOAD_FOLDER")
47
- print("made UPLOAD_FOLDER")
48
- except:
49
- pass
50
-
51
- #Creating static dir to save the generated file
52
- def mk_static_folder():
53
- try:
54
- os.mkdir("static")
55
- print("made static folder")
56
- except:
57
- pass
58
-
59
-
60
- # creating the model instance
61
- model = YOLO('best.pt')
62
-
63
-
64
- def Use_yolo(img_path):
65
- """
66
- :param img_path:
67
- :return: image with bbox , csv file
68
- """
69
- all_data =[]
70
-
71
- results = model(img_path, conf=0.1, verbose=False)
72
- model.predict(img_path, save=True, conf=0.2, show_labels=True,
73
- project='static', name="Image_Prediction")
74
- # Extract bounding boxes, confidence scores, and class labels
75
- boxes = results[0].boxes.xyxy.tolist() # Bounding boxes in xyxy format
76
- classes = results[0].boxes.cls.tolist() # Class indices
77
- confidences = results[0].boxes.conf.tolist() # Confidence scores
78
- names = results[0].names # Class names dictionary
79
-
80
- if not boxes:
81
- # If no detections, add NEG as the class
82
- all_data.append({
83
- 'Class': 'No Object Found', # Default value (no detection)
84
- 'x_min': 'Nan', # Default value (no detection)
85
- 'y_min': 'Nan', # Default value (no detection)
86
- 'x_max': 'Nan', # Default value (no detection)
87
- 'y_max': 'Nan' # Default value (no detection)
88
- })
89
- else:
90
- # Iterate through the results for this image
91
- for box, cls, conf in zip(boxes, classes, confidences):
92
- x_min, y_min, x_max, y_max = box
93
- detected_class = names[int(cls)] # Get the class name from the names dictionary
94
-
95
- # Add the result to the all_data list
96
- all_data.append({
97
- 'Class': detected_class,
98
- 'x_min': int(x_min),
99
- 'y_min': int(y_min),
100
- 'x_max': int(x_max),
101
- 'y_max': int(y_max),
102
- 'Confidence/Probability Score': conf
103
- })
104
-
105
- sub = pd.DataFrame(all_data)
106
-
107
- sub.to_csv("static/CSV_File/WBC_File.csv", index=False)
108
-
109
-
110
- app = Flask(__name__)
111
- app.config['UPLOAD_FOLDER'] = 'UPLOAD_FOLDER'
112
-
113
- @app.route('/')
114
- def home():
115
- return render_template('index.html')
116
-
117
- @app.route('/index')
118
- def home_click():
119
- return render_template('index.html')
120
-
121
- @app.route('/document')
122
- def document_click():
123
- df = pd.read_csv("Documents/results.csv") # Reading CSV File
124
- # Convert DataFrame to a list of dictionaries
125
- data = df.to_dict(orient='records')
126
-
127
- return render_template('document.html', data=data, columns=df.columns)
128
-
129
-
130
- @app.route('/wbc_info')
131
- def wbc_info_click():
132
- return render_template('wbc_info.html')
133
-
134
-
135
- @app.route('/upload', methods=['GET', 'POST'])
136
- def upload():
137
- try:
138
- if request.method == 'POST':
139
-
140
- ## clearing old files and folders and creating Folders for saving file
141
- clr_old_upload()
142
- clr_static()
143
- mk_static_folder()
144
- mk_uploaded_folder()
145
- mk_csv_folder()
146
- show_csv_heading = False ## This is set so that co-ordinates table heading will only whow when it is true
147
- f = request.files['fileInput'] ## geting path of input file
148
-
149
- f.save(os.path.join(app.config["UPLOAD_FOLDER"], secure_filename(f.filename) )) ## saving the input image file in UPLOAD_FOLDER
150
- imageList = os.listdir("UPLOAD_FOLDER") # geting listv of image files in UPLOAD_FOLDER
151
-
152
- for image in imageList:
153
- ### Applying yolo model for object detection on uploaded files
154
- Use_yolo("UPLOAD_FOLDER/"+image)
155
-
156
- pred_image_list = os.listdir("static/Image_Prediction") ## geting the file path of generated image having object detection
157
-
158
- df = pd.read_csv("static/CSV_File/WBC_File.csv") # Reading CSV File
159
- # Convert DataFrame to a list of dictionaries
160
- data = df.to_dict(orient='records')
161
- show_csv_heading = True
162
- return render_template("index.html", pred_image_list= pred_image_list, data=data, columns=df.columns, show_csv_heading=show_csv_heading)
163
-
164
- except:
165
- return render_template("error.html")
166
-
167
- if __name__ == "__main__":
168
- app.run(host='0.0.0.0', port=7860)
169
-
 
 
 
 
 
 
 
 
1
+ # Import libraries
2
+ import pandas as pd
3
+ from ultralytics import YOLO
4
+ from flask import Flask, render_template, request, send_from_directory
5
+ from werkzeug.utils import secure_filename
6
+ import os
7
+ import pandas as pd
8
+ import shutil
9
+
10
+ folder_path = "UPLOAD" # Change this to your desired folder name
11
+
12
+ # Create the folder if it does not exist
13
+ if not os.path.exists(folder_path):
14
+ os.makedirs(folder_path)
15
+ print(f"Folder '{folder_path}' created successfully.")
16
+ else:
17
+ print(f"Folder '{folder_path}' already exists.")
18
+
19
+ def clr_static():
20
+ """
21
+ for removing the static folder (for memoery saving in web)
22
+ """
23
+ dir = 'static'
24
+ try:
25
+ shutil.rmtree(dir)
26
+ print("Cleared Static")
27
+ except:
28
+ pass
29
+
30
+ def clr_old_upload():
31
+ """
32
+ for removing the old images uploaded file (for memoery saving in web)
33
+ """
34
+ dir = 'UPLOAD_FOLDER'
35
+ try:
36
+ shutil.rmtree(dir)
37
+ print("Cleared UPLOAD_FOLDER")
38
+ except:
39
+ pass
40
+
41
+
42
+ #making dir to save the generated csv file
43
+ def mk_csv_folder():
44
+ try:
45
+ os.mkdir("static/CSV_File")
46
+ print("made csv_folder")
47
+ except:
48
+ pass
49
+
50
+ #Creating UPLOAD_FOLDER dir to save the Uploaded file
51
+ def mk_uploaded_folder():
52
+ try:
53
+ os.mkdir("UPLOAD_FOLDER")
54
+ print("made UPLOAD_FOLDER")
55
+ except:
56
+ pass
57
+
58
+ #Creating static dir to save the generated file
59
+ def mk_static_folder():
60
+ try:
61
+ os.mkdir("static")
62
+ print("made static folder")
63
+ except:
64
+ pass
65
+
66
+
67
+ # creating the model instance
68
+ model = YOLO('best.pt')
69
+
70
+
71
+ def Use_yolo(img_path):
72
+ """
73
+ :param img_path:
74
+ :return: image with bbox , csv file
75
+ """
76
+ all_data =[]
77
+
78
+ results = model(img_path, conf=0.1, verbose=False)
79
+ model.predict(img_path, save=True, conf=0.2, show_labels=True,
80
+ project='static', name="Image_Prediction")
81
+ # Extract bounding boxes, confidence scores, and class labels
82
+ boxes = results[0].boxes.xyxy.tolist() # Bounding boxes in xyxy format
83
+ classes = results[0].boxes.cls.tolist() # Class indices
84
+ confidences = results[0].boxes.conf.tolist() # Confidence scores
85
+ names = results[0].names # Class names dictionary
86
+
87
+ if not boxes:
88
+ # If no detections, add NEG as the class
89
+ all_data.append({
90
+ 'Class': 'No Object Found', # Default value (no detection)
91
+ 'x_min': 'Nan', # Default value (no detection)
92
+ 'y_min': 'Nan', # Default value (no detection)
93
+ 'x_max': 'Nan', # Default value (no detection)
94
+ 'y_max': 'Nan' # Default value (no detection)
95
+ })
96
+ else:
97
+ # Iterate through the results for this image
98
+ for box, cls, conf in zip(boxes, classes, confidences):
99
+ x_min, y_min, x_max, y_max = box
100
+ detected_class = names[int(cls)] # Get the class name from the names dictionary
101
+
102
+ # Add the result to the all_data list
103
+ all_data.append({
104
+ 'Class': detected_class,
105
+ 'x_min': int(x_min),
106
+ 'y_min': int(y_min),
107
+ 'x_max': int(x_max),
108
+ 'y_max': int(y_max),
109
+ 'Confidence/Probability Score': conf
110
+ })
111
+
112
+ sub = pd.DataFrame(all_data)
113
+
114
+ sub.to_csv("static/CSV_File/WBC_File.csv", index=False)
115
+
116
+
117
+ app = Flask(__name__)
118
+ app.config['UPLOAD_FOLDER'] = 'UPLOAD_FOLDER'
119
+
120
+ @app.route('/')
121
+ def home():
122
+ return render_template('index.html')
123
+
124
+ @app.route('/index')
125
+ def home_click():
126
+ return render_template('index.html')
127
+
128
+ @app.route('/document')
129
+ def document_click():
130
+ df = pd.read_csv("Documents/results.csv") # Reading CSV File
131
+ # Convert DataFrame to a list of dictionaries
132
+ data = df.to_dict(orient='records')
133
+
134
+ return render_template('document.html', data=data, columns=df.columns)
135
+
136
+
137
+ @app.route('/wbc_info')
138
+ def wbc_info_click():
139
+ return render_template('wbc_info.html')
140
+
141
+
142
+ @app.route('/upload', methods=['GET', 'POST'])
143
+ def upload():
144
+ try:
145
+ if request.method == 'POST':
146
+
147
+ ## clearing old files and folders and creating Folders for saving file
148
+ clr_old_upload()
149
+ clr_static()
150
+ mk_static_folder()
151
+ mk_uploaded_folder()
152
+ mk_csv_folder()
153
+ show_csv_heading = False ## This is set so that co-ordinates table heading will only whow when it is true
154
+ f = request.files['fileInput'] ## geting path of input file
155
+
156
+ f.save(os.path.join(app.config["UPLOAD_FOLDER"], secure_filename(f.filename) )) ## saving the input image file in UPLOAD_FOLDER
157
+ imageList = os.listdir("UPLOAD_FOLDER") # geting listv of image files in UPLOAD_FOLDER
158
+
159
+ for image in imageList:
160
+ ### Applying yolo model for object detection on uploaded files
161
+ Use_yolo("UPLOAD_FOLDER/"+image)
162
+
163
+ pred_image_list = os.listdir("static/Image_Prediction") ## geting the file path of generated image having object detection
164
+
165
+ df = pd.read_csv("static/CSV_File/WBC_File.csv") # Reading CSV File
166
+ # Convert DataFrame to a list of dictionaries
167
+ data = df.to_dict(orient='records')
168
+ show_csv_heading = True
169
+ return render_template("index.html", pred_image_list= pred_image_list, data=data, columns=df.columns, show_csv_heading=show_csv_heading)
170
+
171
+ except:
172
+ return render_template("error.html")
173
+
174
+ if __name__ == "__main__":
175
+ app.run(host='0.0.0.0', port=7860)
176
+