Nav27 commited on
Commit
fdee071
·
verified ·
1 Parent(s): 43ab1c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -81
app.py CHANGED
@@ -4,93 +4,72 @@ import subprocess
4
  import cv2
5
  import matplotlib.pyplot as plt
6
  import glob
7
- import logging
8
 
9
- # Set up logging
10
- logging.basicConfig(level=logging.INFO)
11
- logger = logging.getLogger(__name__)
12
-
13
- def modify_degradations_py():
14
- try:
15
- file_path = '/usr/local/lib/python3.10/site-packages/basicsr/data/degradations.py'
16
- if not os.path.exists(file_path):
17
- logger.warning(f"File not found: {file_path}")
18
- return
19
-
20
- with open(file_path, 'r') as f:
21
- lines = f.readlines()
22
-
23
- for i, line in enumerate(lines):
24
- if 'from torchvision.transforms.functional_tensor import rgb_to_grayscale' in line:
25
- lines[i] = 'from torchvision.transforms.functional import rgb_to_grayscale\n'
26
- break
27
-
28
- with open(file_path, 'w') as f:
29
- f.writelines(lines)
30
- except Exception as e:
31
- logger.error(f"Error modifying degradations.py: {str(e)}")
32
 
 
33
  def display(img1, img2):
34
- try:
35
- fig = plt.figure(figsize=(25, 10))
36
- ax1 = fig.add_subplot(1, 2, 1)
37
- plt.title('Input image', fontsize=16)
38
- ax1.axis('off')
39
- ax2 = fig.add_subplot(1, 2, 2)
40
- plt.title('Image-Blitz output', fontsize=16)
41
- ax2.axis('off')
42
- ax1.imshow(img1)
43
- ax2.imshow(img2)
44
- st.pyplot(fig)
45
- plt.close(fig) # Clean up
46
- except Exception as e:
47
- st.error(f"Error displaying images: {str(e)}")
48
 
 
49
  def imread(img_path):
50
- try:
51
- if not os.path.exists(img_path):
52
- raise FileNotFoundError(f"Image not found: {img_path}")
53
- img = cv2.imread(img_path)
54
- if img is None:
55
- raise ValueError(f"Failed to load image: {img_path}")
56
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
57
- return img
58
- except Exception as e:
59
- logger.error(f"Error reading image: {str(e)}")
60
  return None
 
 
61
 
 
62
  def run_shell_commands():
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  try:
64
- directories = [
65
- "results/cropped_faces",
66
- "results/restored_faces",
67
- "results/restored_imgs",
68
- "results/cmp"
69
- ]
70
-
71
- for directory in directories:
72
- os.makedirs(directory, exist_ok=True)
73
-
74
- command = "python inference_gfpgan.py -i inputs/upload -o results -v 1.3 -s 2 --bg_upsampler realesrgan"
75
  process = subprocess.run(command, shell=True, capture_output=True, text=True)
76
-
77
  if process.returncode != 0:
78
- raise subprocess.CalledProcessError(process.returncode, command, process.stdout, process.stderr)
79
-
80
- return process.stdout
81
  except Exception as e:
82
- logger.error(f"Error in shell commands: {str(e)}")
83
- return None
84
 
 
85
  st.title('Image Enhancer')
86
  st.write('This is a simple web app to enhance the quality of images')
87
  st.write('Kindly wait for 30-40 seconds after uploading a photo 🙂')
88
 
 
89
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
90
 
91
  if uploaded_file is not None:
92
  try:
93
- # Create input directory if it doesn't exist
 
 
 
 
94
  input_path = os.path.join('inputs', 'upload')
95
  os.makedirs(input_path, exist_ok=True)
96
 
@@ -99,13 +78,13 @@ if uploaded_file is not None:
99
  with open(file_path, 'wb') as f:
100
  f.write(uploaded_file.getbuffer())
101
 
102
- st.info("Processing image... Please wait.")
103
 
104
- output = run_shell_commands()
105
- if output is not None:
106
- st.success("Processing complete!")
107
 
108
- # Display images
109
  input_folder = 'results/cropped_faces'
110
  result_folder = 'results/restored_faces'
111
 
@@ -113,7 +92,7 @@ if uploaded_file is not None:
113
  output_list = sorted(glob.glob(os.path.join(result_folder, '*')))
114
 
115
  if not input_list or not output_list:
116
- st.warning("No results found. The image might not contain any faces.")
117
  else:
118
  for input_path, output_path in zip(input_list, output_list):
119
  img_input = imread(input_path)
@@ -122,14 +101,15 @@ if uploaded_file is not None:
122
  display(img_input, img_output)
123
 
124
  # Cleanup
125
- try:
126
  os.remove(file_path)
127
- for path in input_list + output_list:
128
- if os.path.exists(path):
129
- os.remove(path)
130
- except Exception as e:
131
- logger.error(f"Error during cleanup: {str(e)}")
132
-
133
  except Exception as e:
134
- st.error(f"An error occurred: {str(e)}")
135
- logger.error(f"Error processing image: {str(e)}")
 
 
 
 
4
  import cv2
5
  import matplotlib.pyplot as plt
6
  import glob
 
7
 
8
+ st.set_option('deprecation.showPyplotGlobalUse', False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Function to display images side by side
11
  def display(img1, img2):
12
+ fig = plt.figure(figsize=(25, 10))
13
+ ax1 = fig.add_subplot(1, 2, 1)
14
+ plt.title('Input image', fontsize=16)
15
+ ax1.axis('off')
16
+ ax2 = fig.add_subplot(1, 2, 2)
17
+ plt.title('Image-Blitz output', fontsize=16)
18
+ ax2.axis('off')
19
+ ax1.imshow(img1)
20
+ ax2.imshow(img2)
21
+ st.pyplot(fig)
22
+ plt.close(fig)
 
 
 
23
 
24
+ # Function to read an image
25
  def imread(img_path):
26
+ img = cv2.imread(img_path)
27
+ if img is None:
28
+ st.error(f"Failed to load image: {img_path}")
 
 
 
 
 
 
 
29
  return None
30
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
31
+ return img
32
 
33
+ # Function to run shell commands
34
  def run_shell_commands():
35
+ st.info("Creating directories...")
36
+ directories = [
37
+ "results/cropped_faces",
38
+ "results/restored_faces",
39
+ "results/restored_imgs",
40
+ "results/cmp"
41
+ ]
42
+
43
+ for directory in directories:
44
+ os.makedirs(directory, exist_ok=True)
45
+
46
+ st.info("Running image enhancement...")
47
+ command = "python inference_gfpgan.py -i inputs/upload -o results -v 1.3 -s 2 --bg_upsampler realesrgan"
48
  try:
 
 
 
 
 
 
 
 
 
 
 
49
  process = subprocess.run(command, shell=True, capture_output=True, text=True)
 
50
  if process.returncode != 0:
51
+ st.error(f"Command failed with error: {process.stderr}")
52
+ return False
53
+ return True
54
  except Exception as e:
55
+ st.error(f"Failed to run enhancement: {str(e)}")
56
+ return False
57
 
58
+ # Start Streamlit app
59
  st.title('Image Enhancer')
60
  st.write('This is a simple web app to enhance the quality of images')
61
  st.write('Kindly wait for 30-40 seconds after uploading a photo 🙂')
62
 
63
+ # File uploader with progress bar
64
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
65
 
66
  if uploaded_file is not None:
67
  try:
68
+ # Show processing status
69
+ status = st.empty()
70
+ status.info("Processing started...")
71
+
72
+ # Create input directory
73
  input_path = os.path.join('inputs', 'upload')
74
  os.makedirs(input_path, exist_ok=True)
75
 
 
78
  with open(file_path, 'wb') as f:
79
  f.write(uploaded_file.getbuffer())
80
 
81
+ status.info("File uploaded successfully. Processing image...")
82
 
83
+ # Run enhancement
84
+ if run_shell_commands():
85
+ status.success("Processing complete!")
86
 
87
+ # Display results
88
  input_folder = 'results/cropped_faces'
89
  result_folder = 'results/restored_faces'
90
 
 
92
  output_list = sorted(glob.glob(os.path.join(result_folder, '*')))
93
 
94
  if not input_list or not output_list:
95
+ st.warning("No faces detected in the image.")
96
  else:
97
  for input_path, output_path in zip(input_list, output_list):
98
  img_input = imread(input_path)
 
101
  display(img_input, img_output)
102
 
103
  # Cleanup
104
+ if os.path.exists(file_path):
105
  os.remove(file_path)
106
+
107
+ else:
108
+ status.error("Failed to process image.")
109
+
 
 
110
  except Exception as e:
111
+ st.error(f"Error: {str(e)}")
112
+
113
+ finally:
114
+ # Clear status
115
+ status.empty()