KashishG commited on
Commit
b01377c
·
1 Parent(s): 9935513

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +381 -155
app.py CHANGED
@@ -1,157 +1,383 @@
1
- from pathlib import Path
2
- from typing import List, Dict, Tuple
3
- import matplotlib.colors as mpl_colors
4
-
5
- import pandas as pd
6
- import seaborn as sns
7
- import shinyswatch
8
-
9
- import shiny.experimental as x
10
- from shiny import App, Inputs, Outputs, Session, reactive, render, req, ui
11
-
12
- sns.set_theme()
13
-
14
- www_dir = Path(__file__).parent.resolve() / "www"
15
-
16
- df = pd.read_csv(Path(__file__).parent / "penguins.csv", na_values="NA")
17
- numeric_cols: List[str] = df.select_dtypes(include=["float64"]).columns.tolist()
18
- species: List[str] = df["Species"].unique().tolist()
19
- species.sort()
20
-
21
- app_ui = x.ui.page_fillable(
22
- shinyswatch.theme.minty(),
23
- x.ui.layout_sidebar(
24
- x.ui.sidebar(
25
- # Artwork by @allison_horst
26
- ui.input_selectize(
27
- "xvar",
28
- "X variable",
29
- numeric_cols,
30
- selected="Bill Length (mm)",
31
- ),
32
- ui.input_selectize(
33
- "yvar",
34
- "Y variable",
35
- numeric_cols,
36
- selected="Bill Depth (mm)",
37
- ),
38
- ui.input_checkbox_group(
39
- "species", "Filter by species", species, selected=species
40
- ),
41
- ui.hr(),
42
- ui.input_switch("by_species", "Show species", value=True),
43
- ui.input_switch("show_margins", "Show marginal plots", value=True),
44
- ),
45
- ui.output_ui("value_boxes"),
46
- x.ui.output_plot("scatter", fill=True),
47
- ui.help_text(
48
- "Artwork by ",
49
- ui.a("@allison_horst", href="https://twitter.com/allison_horst"),
50
- class_="text-end",
51
- ),
52
- fill=True,
53
- fillable=True,
54
- ),
55
- )
56
-
57
-
58
- def server(input: Inputs, output: Outputs, session: Session):
59
- @reactive.Calc
60
- def filtered_df() -> pd.DataFrame:
61
- """Returns a Pandas data frame that includes only the desired rows"""
62
-
63
- # This calculation "req"uires that at least one species is selected
64
- req(len(input.species()) > 0)
65
-
66
- # Filter the rows so we only include the desired species
67
- return df[df["Species"].isin(input.species())]
68
-
69
- @output
70
- @render.plot
71
- def scatter():
72
- """Generates a plot for Shiny to display to the user"""
73
-
74
- # The plotting function to use depends on whether margins are desired
75
- plotfunc = sns.jointplot if input.show_margins() else sns.scatterplot
76
-
77
- plotfunc(
78
- data=filtered_df(),
79
- x=input.xvar(),
80
- y=input.yvar(),
81
- palette=palette,
82
- hue="Species" if input.by_species() else None,
83
- hue_order=species,
84
- legend=False,
85
  )
86
 
87
- @output
88
- @render.ui
89
- def value_boxes():
90
- df = filtered_df()
91
-
92
- def penguin_value_box(title: str, count: int, bgcol: str, showcase_img: str):
93
- return x.ui.value_box(
94
- title,
95
- count,
96
- {"class_": "pt-1 pb-0"},
97
- showcase=x.ui.bind_fill_role(
98
- ui.tags.img(
99
- {"style": "object-fit:contain;"},
100
- src=showcase_img,
101
- ),
102
- item=True,
103
- ),
104
- theme_color=None,
105
- style=f"background-color: {bgcol};",
106
- height="90px",
107
- full_screen=True,
108
- )
109
-
110
- if not input.by_species():
111
- return penguin_value_box(
112
- "Penguins",
113
- len(df.index),
114
- bg_palette["default"],
115
- # Artwork by @allison_horst
116
- showcase_img="penguins.png",
117
- )
118
-
119
- value_boxes = [
120
- penguin_value_box(
121
- name,
122
- len(df[df["Species"] == name]),
123
- bg_palette[name],
124
- # Artwork by @allison_horst
125
- showcase_img=f"{name}.png",
126
- )
127
- for name in species
128
- # Only include boxes for _selected_ species
129
- if name in input.species()
130
- ]
131
-
132
- return x.ui.layout_column_wrap(1 / len(value_boxes), *value_boxes)
133
-
134
-
135
- # "darkorange", "purple", "cyan4"
136
- colors = [[255, 140, 0], [160, 32, 240], [0, 139, 139]]
137
- colors = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in colors]
138
-
139
- palette: Dict[str, Tuple[float, float, float]] = {
140
- "Adelie": colors[0],
141
- "Chinstrap": colors[1],
142
- "Gentoo": colors[2],
143
- "default": sns.color_palette()[0], # type: ignore
144
- }
145
-
146
- bg_palette = {}
147
- # Use `sns.set_style("whitegrid")` to help find approx alpha value
148
- for name, col in palette.items():
149
- # Adjusted n_colors until `axe` accessibility did not complain about color contrast
150
- bg_palette[name] = mpl_colors.to_hex(sns.light_palette(col, n_colors=7)[1]) # type: ignore
151
-
152
-
153
- app = App(
154
- app_ui,
155
- server,
156
- static_assets=str(www_dir),
157
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import pytesseract
3
+ import os
4
+ import requests
5
+ from flask import Flask, request, jsonify
6
+ from queue import Queue
7
+ from threading import Thread
8
+ from io import BytesIO
9
+ import numpy as np
10
+ import urllib.request
11
+ import requests
12
+ import json
13
+
14
+ app = Flask(__name__)
15
+ image_queue = Queue()
16
+
17
+ # Path to the Tesseract OCR executable (change it to your specific installation path)
18
+ pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
19
+
20
+ # Function to extract text from an image using PyTesseract OCR
21
+ def enhance_contrast(image):
22
+ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
23
+ lab_planes = cv2.split(lab)
24
+ clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(8, 8))
25
+ lab_planes = list(lab_planes)
26
+ lab_planes[0] = clahe.apply(lab_planes[0])
27
+ lab = cv2.merge(lab_planes)
28
+ enhanced_image = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
29
+ return enhanced_image
30
+
31
+ def extract_text_from_image(image):
32
+ enhanced_image = enhance_contrast(image)
33
+ gray = cv2.cvtColor(enhanced_image, cv2.COLOR_BGR2GRAY)
34
+ text = pytesseract.image_to_string(gray)
35
+ return text.strip()
36
+
37
+ def process_image_result(initial_url, final_url, taskId, userId, type):
38
+ if type == 'post-like':
39
+ process_post_like(initial_url, final_url, taskId, userId)
40
+ elif type == 'reel-like':
41
+ process_reel_like(initial_url, final_url, taskId, userId)
42
+ elif type == 'follow':
43
+ process_follow_status(initial_url, final_url, taskId, userId)
44
+ else:
45
+ return
46
+
47
+ # Remove the processed image URLs from the queue
48
+ image_queue.task_done()
49
+
50
+ # Check if there are more images in the queue
51
+ if not image_queue.empty():
52
+ # Get the next image URLs from the queue
53
+ next_image_urls = image_queue.get()
54
+ # Ensure next_image_urls is a dictionary-like object
55
+ if isinstance(next_image_urls, dict):
56
+ # Extract the URLs
57
+ next_initial_url = next_image_urls.get('initial_url')
58
+ next_final_url = next_image_urls.get('final_url')
59
+ next_taskId = next_image_urls.get('taskId')
60
+ next_userId = next_image_urls.get('userId')
61
+ next_type = next_image_urls.get('type')
62
+
63
+ # Process the next image in the queue
64
+ process_image_result(next_initial_url, next_final_url, next_taskId, next_userId, next_type)
65
+ else:
66
+ # All images have been processed
67
+ response_data = jsonify(
68
+ {
69
+ "result":"All images processed"
70
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  )
72
 
73
+ print(response_data.get_json())
74
+
75
+ # # Send the response_data to the specified URL
76
+ # url = 'https://project-b-olive.vercel.app/api/ml/get-result'
77
+ # response = requests.post(url, json=response_data.get_json())
78
+ # print(response.json()) # Print the response from the URL
79
+ # Convert response_data to a JSON string
80
+ response_payload = json.dumps(response_data.get_json())
81
+ headers = {'Content-Type': 'application/json'}
82
+
83
+ # Send the response_payload as the payload to the specified URL
84
+ url = 'https://project-b-olive.vercel.app/api/ml/get-result'
85
+ response = requests.post(url, data=response_payload, headers=headers)
86
+ print(response.json()) # Print the response from the URL
87
+
88
+
89
+ # Function to process the image result
90
+ def process_post_like(initial_url, final_url, taskId, userId):
91
+ with app.app_context():
92
+ try:
93
+ initial_image = urllib.request.urlopen(initial_url)
94
+ final_image = urllib.request.urlopen(final_url)
95
+ initial_np_arr = np.asarray(bytearray(initial_image.read()), dtype=np.uint8)
96
+ final_np_arr = np.asarray(bytearray(final_image.read()), dtype=np.uint8)
97
+ initial_screenshot = cv2.imdecode(initial_np_arr, cv2.IMREAD_COLOR)
98
+ final_screenshot = cv2.imdecode(final_np_arr, cv2.IMREAD_COLOR)
99
+ except Exception as e:
100
+ return jsonify({'status': 'fail', 'code': 500, 'message': str(e)}), 500
101
+
102
+ # Set the region of interest (ROI) coordinates for the like count as a percentage of the screen size
103
+ roi_x = 0 # Convert to percentage
104
+ roi_y = 0 # Convert to percentage
105
+ roi_width = initial_screenshot.shape[1] # Convert to percentage
106
+ roi_height = initial_screenshot.shape[0] # Convert to percentage
107
+
108
+ # Set the region of interest (ROI) for the like count in the initial and final screenshots
109
+ initial_roi = initial_screenshot[int(roi_y * initial_screenshot.shape[0] / 100):int((roi_y + roi_height) * initial_screenshot.shape[0] / 100),
110
+ int(roi_x * initial_screenshot.shape[1] / 100):int((roi_x + roi_width) * initial_screenshot.shape[1] / 100)]
111
+ final_roi = final_screenshot[int(roi_y * final_screenshot.shape[0] / 100):int((roi_y + roi_height) * final_screenshot.shape[0] / 100),
112
+ int(roi_x * final_screenshot.shape[1] / 100):int((roi_x + roi_width) * final_screenshot.shape[1] / 100)]
113
+
114
+ initial_red_pixels = np.sum(initial_roi[:, :, 2] > 0)
115
+ final_red_pixels = np.sum(final_roi[:, :, 2] > 0)
116
+
117
+ if final_red_pixels > initial_red_pixels:
118
+ result = "User liked the post!"
119
+ user_liked = 1
120
+ elif final_red_pixels < initial_red_pixels:
121
+ result = "User unliked the post."
122
+ user_liked = 0
123
+ else:
124
+ result = "No change in like status."
125
+ user_liked = 0
126
+
127
+ # response_data = jsonify({'status': 'success', 'code': 200, 'message': result, 'data': {'result': user_liked, 'taskId': taskId, 'userId': userId}})
128
+
129
+ response_data = jsonify(
130
+ {
131
+ "taskId": taskId,
132
+ "userId": userId,
133
+ "result": user_liked
134
+ }
135
+ )
136
+
137
+ print(response_data.get_json())
138
+
139
+ # # Send the response_data to the specified URL
140
+ # url = 'https://project-b-olive.vercel.app/api/ml/get-result'
141
+ # response = requests.post(url, json=response_data.get_json())
142
+ # print(response.json()) # Print the response from the URL
143
+ # Convert response_data to a JSON string
144
+ response_payload = json.dumps(response_data.get_json())
145
+ headers = {'Content-Type': 'application/json'}
146
+
147
+ # Send the response_payload as the payload to the specified URL
148
+ url = 'https://project-b-olive.vercel.app/api/ml/get-result'
149
+ response = requests.post(url, data=response_payload, headers=headers)
150
+ print(response.json()) # Print the response from the URL
151
+
152
+
153
+
154
+
155
+
156
+ def process_reel_like(initial_url, final_url, taskId, userId):
157
+ with app.app_context():
158
+ try:
159
+ initial_image = urllib.request.urlopen(initial_url)
160
+ final_image = urllib.request.urlopen(final_url)
161
+ initial_np_arr = np.asarray(bytearray(initial_image.read()), dtype=np.uint8)
162
+ final_np_arr = np.asarray(bytearray(final_image.read()), dtype=np.uint8)
163
+ initial_screenshot = cv2.imdecode(initial_np_arr, cv2.IMREAD_COLOR)
164
+ final_screenshot = cv2.imdecode(final_np_arr, cv2.IMREAD_COLOR)
165
+ except Exception as e:
166
+ return jsonify({'status': 'fail', 'code': 500, 'message': str(e)}), 500
167
+
168
+ # Set the region of interest (ROI) coordinates for the like count as a percentage of the screen size
169
+ roi_x = 0 # Convert to percentage
170
+ roi_y = 75 # Convert to percentage
171
+ roi_width = initial_screenshot.shape[1] # Convert to percentage
172
+ roi_height =10 # Convert to percentage
173
+
174
+ # Set the region of interest (ROI) for the like count in the initial and final screenshots
175
+ initial_roi = initial_screenshot[int(roi_y * initial_screenshot.shape[0] / 100):int((roi_y + roi_height) * initial_screenshot.shape[0] / 100),
176
+ int(roi_x * initial_screenshot.shape[1] / 100):int((roi_x + roi_width) * initial_screenshot.shape[1] / 100)]
177
+ final_roi = final_screenshot[int(roi_y * final_screenshot.shape[0] / 100):int((roi_y + roi_height) * final_screenshot.shape[0] / 100),
178
+ int(roi_x * final_screenshot.shape[1] / 100):int((roi_x + roi_width) * final_screenshot.shape[1] / 100)]
179
+
180
+ cv2.imshow("Initial ROI", initial_roi)
181
+
182
+ cv2.waitKey(0)
183
+ cv2.destroyAllWindows()
184
+
185
+ initial_red_pixels = np.sum(initial_roi[:, :, 2] )
186
+ final_red_pixels = np.sum(final_roi[:, :, 2])
187
+
188
+ if final_red_pixels > initial_red_pixels:
189
+ result = "User liked the post!"
190
+ user_liked = 1
191
+ elif final_red_pixels < initial_red_pixels:
192
+ result = "User unliked the post."
193
+ user_liked = 0
194
+ else:
195
+ result = "No change in like status."
196
+ user_liked = 0
197
+
198
+ # response_data = jsonify({'status': 'success', 'code': 200, 'message': result, 'data': {'result': user_liked, 'taskId': taskId, 'userId': userId}})
199
+
200
+ response_data = jsonify(
201
+ {
202
+ "taskId": taskId,
203
+ "userId": userId,
204
+ "result": user_liked
205
+ }
206
+ )
207
+
208
+ print(response_data.get_json())
209
+
210
+ # # Send the response_data to the specified URL
211
+ # url = 'https://project-b-olive.vercel.app/api/ml/get-result'
212
+ # response = requests.post(url, json=response_data.get_json())
213
+ # print(response.json()) # Print the response from the URL
214
+ # Convert response_data to a JSON string
215
+ response_payload = json.dumps(response_data.get_json())
216
+ headers = {'Content-Type': 'application/json'}
217
+
218
+ # Send the response_payload as the payload to the specified URL
219
+ url = 'https://project-b-olive.vercel.app/api/ml/get-result'
220
+ response = requests.post(url, data=response_payload, headers=headers)
221
+ print(response.json()) # Print the response from the URL
222
+
223
+
224
+
225
+ # def process_comment_status(initial_url, final_url, taskId, userId):
226
+ # with app.app_context():
227
+ # try:
228
+ # initial_image_response = requests.get(initial_url)
229
+ # initial_image_np_arr = np.asarray(bytearray(initial_image_response.content), dtype=np.uint8)
230
+ # initial_image = cv2.imdecode(initial_image_np_arr, cv2.IMREAD_COLOR)
231
+
232
+ # final_image_response = requests.get(final_url)
233
+ # final_image_np_arr = np.asarray(bytearray(final_image_response.content), dtype=np.uint8)
234
+ # final_image = cv2.imdecode(final_image_np_arr, cv2.IMREAD_COLOR)
235
+ # except Exception as e:
236
+ # return jsonify({'status': 'fail', 'code': 500, 'message': str(e)}), 500
237
+
238
+ # # Set the region of interest (ROI) coordinates for the comment text as a percentage of the image size
239
+ # roi_x = 0 # Convert to percentage
240
+ # roi_y = 75 # Convert to percentage
241
+ # roi_width = initial_image.shape[1] # Convert to percentage
242
+ # roi_height = 10 # Convert to percentage
243
+
244
+ # # Set the region of interest (ROI) for the comment text in the initial and final images
245
+ # initial_roi = initial_image[int(roi_y * initial_image.shape[0] / 100):int((roi_y + roi_height) * initial_image.shape[0] / 100),
246
+ # int(roi_x * initial_image.shape[1] / 100):int((roi_x + roi_width) * initial_image.shape[1] / 100)]
247
+
248
+ # final_roi = final_image[int(roi_y * final_image.shape[0] / 100):int((roi_y + roi_height) * final_image.shape[0] / 100),
249
+ # int(roi_x * final_image.shape[1] / 100):int((roi_x + roi_width) * final_image.shape[1] / 100)]
250
+
251
+ # initial_comment_text = extract_text_from_image(initial_roi)
252
+ # final_comment_text = extract_text_from_image(final_roi)
253
+
254
+ # if len(initial_comment_text) > 0 or len(final_comment_text) > 0:
255
+ # result = "User commented"
256
+ # user_commented = 1
257
+ # else:
258
+ # result = "No comment"
259
+ # user_commented = 0
260
+
261
+ # response_data = jsonify({
262
+ # "taskId": taskId,
263
+ # "userId": userId,
264
+ # "result": user_commented
265
+ # })
266
+
267
+ # print(response_data.get_json())
268
+
269
+ # # # Send the response_data to the specified URL
270
+ # # url = 'https://project-b-olive.vercel.app/api/ml/get-result'
271
+ # # response = requests.post(url, json=response_data.get_json())
272
+ # # print(response.json()) # Print the response from the URL
273
+ # # Convert response_data to a JSON string
274
+ # response_payload = json.dumps(response_data.get_json())
275
+ # headers = {'Content-Type': 'application/json'}
276
+
277
+ # # Send the response_payload as the payload to the specified URL
278
+ # url = 'https://project-b-olive.vercel.app/api/ml/get-result'
279
+ # response = requests.post(url, data=response_payload, headers=headers)
280
+ # print(response.json()) # Print the response from the URL
281
+
282
+ # image_queue.task_done()
283
+
284
+ def process_follow_status(initial_url, final_url, taskId, userId):
285
+ with app.app_context():
286
+ try:
287
+ initial_image_response = requests.get(initial_url)
288
+ initial_image_np_arr = np.asarray(bytearray(initial_image_response.content), dtype=np.uint8)
289
+ initial_image = cv2.imdecode(initial_image_np_arr, cv2.IMREAD_COLOR)
290
+
291
+ final_image_response = requests.get(final_url)
292
+ final_image_np_arr = np.asarray(bytearray(final_image_response.content), dtype=np.uint8)
293
+ final_image = cv2.imdecode(final_image_np_arr, cv2.IMREAD_COLOR)
294
+ except Exception as e:
295
+ return jsonify({'status': 'fail', 'code': 500, 'message': str(e)}), 500
296
+ height, width, _ = initial_image.shape
297
+ # Set the region of interest (ROI) coordinates for the follow button as a percentage of the screen size
298
+ roi_x = 0 # Convert to percentage
299
+ roi_y = 0 # Convert to percentage
300
+ roi_width = width # Convert to percentage
301
+ roi_height =30 # Convert to percentage
302
+
303
+ # Set the region of interest (ROI) for the follow button in the initial and final screenshots
304
+ initial_roi = initial_image[int(roi_y * height / 100):int((roi_y + roi_height) * height / 100),
305
+ int(roi_x * width / 100):int((roi_x + roi_width) * width / 100)]
306
+ final_roi = final_image[int(roi_y * height / 100):int((roi_y + roi_height) * height / 100),
307
+ int(roi_x * width / 100):int((roi_x + roi_width) * width / 100)]
308
+
309
+ # Apply OCR to extract text from the region of interest in the initial and final screenshots
310
+ initial_text = extract_text_from_image(initial_roi)
311
+ final_text = extract_text_from_image(final_roi)
312
+
313
+
314
+
315
+ # Process the extracted text to consider only the following text
316
+ # initial_text = initial_text.split("Following", 1)[-1].strip()
317
+ # final_text = final_text.split("Following", 1)[-1].strip()
318
+
319
+ # Check if the follow button text has changed from the initial to the final screenshot
320
+ result = ""
321
+ if "Follow" in initial_text and "Following" in final_text and "Following" not in initial_text:
322
+ result = "User followed on Instagram!"
323
+ user_followed = 1
324
+ elif "Following" in initial_text and "Follow" in final_text and "Following" not in final_text:
325
+ result = "User unfollowed on Instagram!"
326
+ user_followed = 0
327
+ else:
328
+ result = "No change in follow status."
329
+ user_followed = 0
330
+
331
+ response_data = jsonify({
332
+ "taskId": taskId,
333
+ "userId": userId,
334
+ "result": user_followed
335
+ })
336
+
337
+ print(response_data.get_json())
338
+
339
+ # # Send the response_data to the specified URL
340
+ # url = 'https://project-b-olive.vercel.app/api/ml/get-result'
341
+ # response = requests.post(url, json=response_data.get_json())
342
+ # print(response.json()) # Print the response from the URL
343
+ # Convert response_data to a JSON string
344
+ response_payload = json.dumps(response_data.get_json())
345
+ headers = {'Content-Type': 'application/json'}
346
+
347
+ # Send the response_payload as the payload to the specified URL
348
+ url = 'https://project-b-olive.vercel.app/api/ml/get-result'
349
+ response = requests.post(url, data=response_payload, headers=headers)
350
+ print(response.json()) # Print the response from the URL
351
+
352
+
353
+
354
+
355
+ @app.route('/receive-image', methods=['POST'])
356
+ def receive_image():
357
+ initial_url = request.json['initial_url']
358
+ final_url = request.json['final_url']
359
+ taskId = request.json['taskId']
360
+ userId = request.json['userId']
361
+ type = request.json['type']
362
+
363
+ # Add the image URLs and task_id to the queue
364
+ image_queue.put((initial_url, final_url, taskId, userId, type))
365
+
366
+ process_thread = Thread(target=process_image_result, args=(initial_url, final_url, taskId, userId, type))
367
+ process_thread.start()
368
+
369
+
370
+ return jsonify({'status': 'success', 'code': 200, 'message': 'Images received',
371
+ 'data': {'received': 1, 'queue_position': image_queue.qsize(), 'task_id': taskId, 'userId': userId}}), 200
372
+
373
+
374
+ @app.errorhandler(404)
375
+ def not_found_error(error):
376
+ return jsonify({'status': 'error', 'code': 404, 'message': 'Resource not found'}), 404
377
+
378
+ @app.errorhandler(500)
379
+ def internal_server_error(error):
380
+ return jsonify({'status': 'fail', 'code': 500, 'message': 'Internal server error'}), 500
381
+
382
+ if __name__ == '__main__':
383
+ app.run(debug=True)