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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -85
app.py CHANGED
@@ -4,110 +4,132 @@ import subprocess
4
  import cv2
5
  import matplotlib.pyplot as plt
6
  import glob
 
7
 
 
 
 
8
 
9
  def modify_degradations_py():
10
- file_path = '/usr/local/lib/python3.10/site-packages/basicsr/data/degradations.py'
11
- with open(file_path, 'r') as f:
12
- lines = f.readlines()
13
-
14
- # Find the line containing 'from torchvision.transforms.functional_tensor import rgb_to_grayscale'
15
- for i, line in enumerate(lines):
16
- if 'from torchvision.transforms.functional_tensor import rgb_to_grayscale' in line:
17
- # Replace it with 'from torchvision.transforms.functional import rgb_to_grayscale'
18
- lines[i] = 'from torchvision.transforms.functional import rgb_to_grayscale\n'
19
- break
20
-
21
- with open(file_path, 'w') as f:
22
- f.writelines(lines)
23
 
24
- # Call the function to modify the file
25
- modify_degradations_py()
 
 
26
 
 
 
 
 
27
 
28
- # Function to display images side by side
29
  def display(img1, img2):
30
- fig = plt.figure(figsize=(25, 10))
31
- ax1 = fig.add_subplot(1, 2, 1)
32
- plt.title('Input image', fontsize=16)
33
- ax1.axis('off')
34
- ax2 = fig.add_subplot(1, 2, 2)
35
- plt.title('Image-Blitz output', fontsize=16)
36
- ax2.axis('off')
37
- ax1.imshow(img1)
38
- ax2.imshow(img2)
39
- st.pyplot(fig)
 
 
 
 
40
 
41
- # Function to read an image
42
  def imread(img_path):
43
- img = cv2.imread(img_path)
44
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
45
- return img
 
 
 
 
 
 
 
 
46
 
47
- # Function to run shell commands
48
  def run_shell_commands():
49
- directories = [
50
- "results/cropped_faces",
51
- "results/restored_faces",
52
- "results/restored_imgs",
53
- "results/cmp"
54
- ]
55
-
56
- # Create directories using os.makedirs()
57
- for directory in directories:
58
- os.makedirs(directory, exist_ok=True)
59
-
60
- # Run inference command
61
- command = "python inference_gfpgan.py -i inputs/upload -o results -v 1.3 -s 2 --bg_upsampler realesrgan"
62
- subprocess.run(command, shell=True, check=True)
63
-
64
- # List the contents of the results/cmp directory
65
- cmp_contents = subprocess.run("dir results\\cmp", shell=True, capture_output=True, text=True)
66
- if cmp_contents.returncode != 0:
67
- #st.error(f"Error listing contents of results/cmp: {cmp_contents.stderr}")
68
- return ""
69
- return cmp_contents.stdout
70
 
71
- # Start Streamlit app
72
  st.title('Image Enhancer')
73
  st.write('This is a simple web app to enhance the quality of images')
74
  st.write('Kindly wait for 30-40 seconds after uploading a photo 🙂')
75
 
76
- # Ask the user to input a file
77
- uploaded_file = st.file_uploader("Choose an image...", type="jpg")
78
 
79
  if uploaded_file is not None:
80
- # Save the uploaded file to the inputs/upload directory
81
- input_path = os.path.join('inputs', 'upload')
82
- if not os.path.exists(input_path):
83
- os.makedirs(input_path)
84
-
85
- file_path = os.path.join(input_path, uploaded_file.name)
86
- with open(file_path, 'wb') as f:
87
- f.write(uploaded_file.getbuffer())
88
-
89
- # Run shell commands
90
  try:
91
- output = run_shell_commands()
92
- # Display the results
93
- st.write('Contents of results/cmp:')
94
- st.text(output)
95
-
96
- # Display images
97
- input_folder = 'results/cropped_faces'
98
- result_folder = 'results/restored_faces'
99
- input_list = sorted(glob.glob(os.path.join(input_folder, '*')))
100
- output_list = sorted(glob.glob(os.path.join(result_folder, '*')))
101
 
102
- for input_path, output_path in zip(input_list, output_list):
103
- img_input = imread(input_path)
104
- img_output = imread(output_path)
105
- display(img_input, img_output)
106
- os.remove(file_path)
107
- os.remove(input_path)
108
- os.remove(output_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
- except subprocess.CalledProcessError as e:
111
- st.error(f"Command failed with error: {e.stderr}")
 
 
 
 
 
 
 
112
  except Exception as e:
113
- st.error(f"An unexpected error occurred: {str(e)}")
 
 
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
+
97
+ # Save uploaded file
98
+ file_path = os.path.join(input_path, uploaded_file.name)
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
+
112
+ input_list = sorted(glob.glob(os.path.join(input_folder, '*')))
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)
120
+ img_output = imread(output_path)
121
+ if img_input is not None and img_output 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)}")