nguyen-brat commited on
Commit
a8ab437
·
1 Parent(s): 35ca994
Files changed (1) hide show
  1. app.py +78 -68
app.py CHANGED
@@ -5,13 +5,27 @@ import subprocess
5
  import zipfile
6
  import io
7
  import shutil
8
- import time
9
  import sys
10
  from PIL import Image
11
  import tempfile
12
 
13
  os.environ["HYDRA_FULL_ERROR"] = "1"
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  def run_bash_script(input_image_path, output_path, progress_placeholder, status_text):
16
  bash_command = f"bash config/text_detection.sh -s {input_image_path} -t {output_path}"
17
  process = subprocess.Popen(bash_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
@@ -22,6 +36,7 @@ def run_bash_script(input_image_path, output_path, progress_placeholder, status_
22
  progress += 0.1
23
  progress_placeholder.progress(min(progress, 1.0))
24
 
 
25
  stderr_output = process.stderr.read()
26
  if stderr_output:
27
  status_text.error("Error output:")
@@ -43,6 +58,17 @@ def zip_result_files(result_folder):
43
 
44
  return zip_buffer
45
 
 
 
 
 
 
 
 
 
 
 
 
46
  def create_temp_structure():
47
  # Create a temporary directory
48
  temp_dir = tempfile.mkdtemp()
@@ -59,83 +85,67 @@ def create_temp_structure():
59
 
60
  return temp_dir, test_folder, target_folder
61
 
62
- def clear_temp_folder(temp_dir):
63
- if temp_dir and os.path.exists(temp_dir):
64
- shutil.rmtree(temp_dir, ignore_errors=True)
65
- st.success("Temporary files have been cleared.")
66
-
67
  st.title("Text Detection App")
68
-
69
- # Use session state to store the temporary directory path
70
- if 'temp_dir' not in st.session_state:
71
- st.session_state.temp_dir = None
72
-
73
  uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
74
 
75
  if uploaded_file is not None:
76
  st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
77
 
78
- # Create a temporary directory for processing if it doesn't exist
79
- if not st.session_state.temp_dir:
80
- temp_dir, input_path, output_path = create_temp_structure()
81
- st.session_state.temp_dir = temp_dir
82
- st.session_state.input_path = input_path
83
- st.session_state.output_path = output_path
84
- else:
85
- temp_dir = st.session_state.temp_dir
86
- input_path = st.session_state.input_path
87
- output_path = st.session_state.output_path
88
-
89
- st.write(f"Temp dir: {temp_dir}")
90
 
91
  input_file_path = os.path.join(input_path, uploaded_file.name)
92
  image = Image.open(uploaded_file)
 
93
  image.save(input_file_path)
94
-
95
- if st.button("Run Text Detection"):
96
- progress_placeholder = st.empty()
97
- status_text = st.empty()
98
-
99
- try:
100
- status_text.text("Running text detection...")
101
- rc, stderr_output = run_bash_script(input_path, output_path, progress_placeholder, status_text)
102
- if rc == 0:
103
- status_text.text("Text detection completed successfully!")
104
- result_folder = os.path.join(output_path, "result")
105
- if os.path.exists(result_folder):
106
- st.write("You can now download the results.")
107
-
108
- # Add download button
109
- zip_buffer = zip_result_files(result_folder)
110
- st.download_button(
111
- label="Download Results",
112
- data=zip_buffer.getvalue(),
113
- file_name="text_detection_results.zip",
114
- mime="application/zip",
115
- on_click=lambda: clear_temp_folder(st.session_state.temp_dir)
116
- )
117
- else:
118
- st.error("Result folder not found. The text detection might have failed.")
119
- else:
120
- st.error(f"Text detection failed with return code {rc}")
121
- if stderr_output:
122
- st.error("Error details:")
123
- st.code(stderr_output, language="bash")
124
- except Exception as e:
125
- st.error(f"An error occurred: {str(e)}")
126
- finally:
127
- progress_placeholder.empty()
128
- status_text.empty()
129
 
130
- # Display directory contents for debugging
131
- if st.session_state.temp_dir:
132
- st.write(f"Contents of temp directory:")
133
- for root, dirs, files in os.walk(st.session_state.temp_dir):
134
- level = root.replace(st.session_state.temp_dir, '').count(os.sep)
135
- indent = ' ' * 4 * (level)
136
- st.write(f"{indent}{os.path.basename(root)}/")
137
- subindent = ' ' * 4 * (level + 1)
138
- for f in files:
139
- st.write(f"{subindent}{f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  st.write("Note: The download button will appear after running text detection.")
 
5
  import zipfile
6
  import io
7
  import shutil
 
8
  import sys
9
  from PIL import Image
10
  import tempfile
11
 
12
  os.environ["HYDRA_FULL_ERROR"] = "1"
13
 
14
+ def GET_PROJECT_ROOT():
15
+ count = 0
16
+ # goto the root folder of LogBar
17
+ current_abspath = os.path.abspath(__file__)
18
+ while True:
19
+ if count > 1000:
20
+ print("Can find root error")
21
+ sys.exit()
22
+ if os.path.split(current_abspath)[1] == 'text-remove':
23
+ project_root = current_abspath
24
+ break
25
+ else:
26
+ current_abspath = os.path.dirname(current_abspath)
27
+ return project_root
28
+
29
  def run_bash_script(input_image_path, output_path, progress_placeholder, status_text):
30
  bash_command = f"bash config/text_detection.sh -s {input_image_path} -t {output_path}"
31
  process = subprocess.Popen(bash_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
 
36
  progress += 0.1
37
  progress_placeholder.progress(min(progress, 1.0))
38
 
39
+ # Capture and display stderr
40
  stderr_output = process.stderr.read()
41
  if stderr_output:
42
  status_text.error("Error output:")
 
58
 
59
  return zip_buffer
60
 
61
+ def clear_folder(folder_path):
62
+ for filename in os.listdir(folder_path):
63
+ file_path = os.path.join(folder_path, filename)
64
+ try:
65
+ if os.path.isfile(file_path) or os.path.islink(file_path):
66
+ os.unlink(file_path) # Remove file or symlink
67
+ elif os.path.isdir(file_path):
68
+ shutil.rmtree(file_path, ignore_errors=True) # Remove directory and its contents
69
+ except Exception as e:
70
+ print(f'Failed to delete {file_path}. Reason: {e}')
71
+
72
  def create_temp_structure():
73
  # Create a temporary directory
74
  temp_dir = tempfile.mkdtemp()
 
85
 
86
  return temp_dir, test_folder, target_folder
87
 
 
 
 
 
 
88
  st.title("Text Detection App")
89
+ # file_name = " || ".join(os.listdir('craft_pytorch'))
90
+ # st.write(file_name)
 
 
 
91
  uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
92
 
93
  if uploaded_file is not None:
94
  st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
95
 
96
+ # Create a temporary directory for processing
97
+
98
+ # Save the uploaded file temporarily
99
+ temp_dir, input_path, output_path = create_temp_structure()
100
+ # st.write(f"Temp dir: {temp_dir}")
101
+ # os.makedirs(input_path, exist_ok=True)
102
+ # os.makedirs(osp(output_path, "result"), exist_ok=True)
103
+ # os.makedirs(osp(output_path, "mask"), exist_ok=True)
 
 
 
 
104
 
105
  input_file_path = os.path.join(input_path, uploaded_file.name)
106
  image = Image.open(uploaded_file)
107
+ # image.save(os.path.join(PROJECT_ROOT, input_file_path))
108
  image.save(input_file_path)
109
+ # file_name = " || ".join(os.listdir(f'{temp_dir}/target_folder'))
110
+ # st.write(file_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+
113
+ progress_placeholder = st.empty()
114
+ status_text = st.empty()
115
+
116
+ status_text.text("Running text detection...")
117
+ st.write(f'the input file path {input_path}')
118
+ st.write(f'the output file path {output_path}')
119
+ #os.makedirs(input_path, exist_ok=True)
120
+ #os.makedirs(osp(output_path, "result"), exist_ok=True)
121
+ #os.makedirs(osp(output_path, "mask"), exist_ok=True)
122
+ rc, stderr_output = run_bash_script(input_path, output_path, progress_placeholder, status_text)
123
+ mask_file_name = " || ".join(os.listdir('{temp_dir}/target_folder/mask'))
124
+ bbox_file_name = " || ".join(os.listdir('{temp_dir}/target_folder/bbox'))
125
+ result_file_name = " || ".join(os.listdir('{temp_dir}/target_folder/bbox'))
126
+ print(f'mask_file_name: {mask_file_name}')
127
+ print(f'bbox_file_name: {bbox_file_name}')
128
+ print(f'result_file_name: {result_file_name}')
129
+ if rc == 0:
130
+ st.write("Text detection completed successfully!")
131
+ status_text.text("Text detection completed successfully!")
132
+ result_folder = os.path.join(output_path, "result")
133
+ if os.path.exists(result_folder):
134
+ st.write("You can now download the results.")
135
+ # Add download button
136
+ zip_buffer = zip_result_files(result_folder)
137
+ st.download_button(
138
+ label="Download Results",
139
+ data=zip_buffer.getvalue(),
140
+ file_name="text_detection_results.zip",
141
+ mime="application/zip"
142
+ )
143
+ else:
144
+ st.error("Result folder not found. The text detection might have failed.")
145
+ else:
146
+ st.error(f"Text detection failed with return code {rc}")
147
+ if stderr_output:
148
+ st.error("Error details:")
149
+ st.code(stderr_output, language="bash")
150
 
151
  st.write("Note: The download button will appear after running text detection.")