cormort commited on
Commit
30548fc
·
verified ·
1 Parent(s): 6f4e0a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -34
app.py CHANGED
@@ -1,92 +1,102 @@
1
  import gradio as gr
2
  import zipfile
 
3
  import os
4
  import tempfile
5
  import shutil
6
  from datetime import datetime
7
 
8
- def process_zips(uploaded_files, position, options, custom_text):
9
  if not uploaded_files:
10
  return []
11
 
12
  processed_files = []
13
  temp_dir = tempfile.mkdtemp()
14
 
15
- # 取得當前時間,確保同一批處理的檔案時間戳記一致
16
  current_time_str = datetime.now().strftime("%Y%m%d_%H%M%S")
17
 
18
  for file_path in uploaded_files:
19
  filename = os.path.basename(file_path)
 
20
 
21
- if not filename.lower().endswith('.zip'):
 
22
  continue
23
 
24
- zip_basename = os.path.splitext(filename)[0]
25
- extract_dir = os.path.join(temp_dir, zip_basename)
26
  os.makedirs(extract_dir, exist_ok=True)
27
 
 
28
  try:
29
- with zipfile.ZipFile(file_path, 'r') as zip_ref:
30
- zip_ref.extractall(extract_dir)
31
- except zipfile.BadZipFile:
32
- print(f"無法讀取壓縮檔: {filename}")
 
 
 
 
33
  continue
34
 
35
- renamed_dir = os.path.join(temp_dir, f"{zip_basename}_renamed")
36
  os.makedirs(renamed_dir, exist_ok=True)
37
 
38
- # 根據使用者的勾選,組合要增加的文字
39
  components = []
40
  if "壓縮檔名" in options:
41
- components.append(zip_basename)
42
  if "日期時間" in options:
43
  components.append(current_time_str)
44
  if "自訂文字" in options and custom_text.strip():
45
  components.append(custom_text.strip())
46
 
47
- # 將選取的元素用底線連接 (例如: zipname_20231025_120000_mytext)
48
  add_str = "_".join(components)
49
 
 
50
  for root, dirs, files in os.walk(extract_dir):
51
  for f in files:
52
  old_path = os.path.join(root, f)
53
 
54
- # 如果使用者什麼都沒勾,或是自訂文字留白,就不做更改
55
  if not add_str:
56
  new_filename = f
57
  else:
58
  if position == "前綴":
59
- # 加在最前面: 附加文字_原檔名
60
  new_filename = f"{add_str}_{f}"
61
  else:
62
- # 後綴 (加在副檔名之前): 原檔名_附加文字.副檔名
63
- name, ext = os.path.splitext(f)
64
- new_filename = f"{name}_{add_str}{ext}"
65
 
66
  new_path = os.path.join(renamed_dir, new_filename)
67
  shutil.copy2(old_path, new_path)
68
 
69
- # 將重新命名後的檔案打包成 ZIP 檔
70
- output_zip_name = f"processed_{filename}"
71
- output_zip_path = os.path.join(temp_dir, output_zip_name)
72
 
73
- with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as out_zip:
74
- for root, dirs, files in os.walk(renamed_dir):
75
- for f in files:
76
- file_to_zip = os.path.join(root, f)
77
- out_zip.write(file_to_zip, arcname=f)
 
 
 
 
 
 
 
78
 
79
- processed_files.append(output_zip_path)
80
 
81
  return processed_files
82
 
83
  # 建立 Gradio 網頁介面
84
  with gr.Blocks(title="壓縮檔內容批次重新命名工具", theme=gr.themes.Soft()) as demo:
85
- gr.Markdown("## 📦 壓縮檔內容批次重新命名工具 (進階版)")
86
- gr.Markdown("上傳 ZIP 檔案後,自訂你想增加的文字與位置。系統處理完畢後會提供 ZIP 檔下載。")
87
 
88
  with gr.Row():
89
- # 左側:設定區
90
  with gr.Column(scale=1):
91
  gr.Markdown("### ⚙️ 命名規則設定")
92
  position_radio = gr.Radio(
@@ -109,16 +119,15 @@ with gr.Blocks(title="壓縮檔內容批次重新命名工具", theme=gr.themes.
109
  info="需在上方勾選「自訂文字」才會生效"
110
  )
111
 
112
- # 右側:檔案上傳區
113
  with gr.Column(scale=1):
114
  gr.Markdown("### 📂 檔案上傳與下載")
115
- file_input = gr.File(label="上傳壓縮檔 (可多)", file_count="multiple", type="filepath", file_types=[".zip"])
 
116
  submit_btn = gr.Button("🚀 開始處理", variant="primary")
117
  file_output = gr.File(label="下載處理後的新壓縮檔")
118
 
119
- # 綁定按鈕點擊事件,傳入所有設定值
120
  submit_btn.click(
121
- fn=process_zips,
122
  inputs=[file_input, position_radio, options_checkbox, custom_text_input],
123
  outputs=file_output
124
  )
 
1
  import gradio as gr
2
  import zipfile
3
+ import py7zr
4
  import os
5
  import tempfile
6
  import shutil
7
  from datetime import datetime
8
 
9
+ def process_archives(uploaded_files, position, options, custom_text):
10
  if not uploaded_files:
11
  return []
12
 
13
  processed_files = []
14
  temp_dir = tempfile.mkdtemp()
15
 
 
16
  current_time_str = datetime.now().strftime("%Y%m%d_%H%M%S")
17
 
18
  for file_path in uploaded_files:
19
  filename = os.path.basename(file_path)
20
+ ext = os.path.splitext(filename)[1].lower()
21
 
22
+ # 確保是 zip 或 7z 檔
23
+ if ext not in ['.zip', '.7z']:
24
  continue
25
 
26
+ archive_basename = os.path.splitext(filename)[0]
27
+ extract_dir = os.path.join(temp_dir, archive_basename)
28
  os.makedirs(extract_dir, exist_ok=True)
29
 
30
+ # 根據副檔名選擇解壓縮方式
31
  try:
32
+ if ext == '.zip':
33
+ with zipfile.ZipFile(file_path, 'r') as zip_ref:
34
+ zip_ref.extractall(extract_dir)
35
+ elif ext == '.7z':
36
+ with py7zr.SevenZipFile(file_path, mode='r') as z_ref:
37
+ z_ref.extractall(path=extract_dir)
38
+ except Exception as e:
39
+ print(f"無法讀取壓縮檔 {filename}: {e}")
40
  continue
41
 
42
+ renamed_dir = os.path.join(temp_dir, f"{archive_basename}_renamed")
43
  os.makedirs(renamed_dir, exist_ok=True)
44
 
45
+ # 組合要增加的文字
46
  components = []
47
  if "壓縮檔名" in options:
48
+ components.append(archive_basename)
49
  if "日期時間" in options:
50
  components.append(current_time_str)
51
  if "自訂文字" in options and custom_text.strip():
52
  components.append(custom_text.strip())
53
 
 
54
  add_str = "_".join(components)
55
 
56
+ # 重新命名檔案並攤平放到新資料夾
57
  for root, dirs, files in os.walk(extract_dir):
58
  for f in files:
59
  old_path = os.path.join(root, f)
60
 
 
61
  if not add_str:
62
  new_filename = f
63
  else:
64
  if position == "前綴":
 
65
  new_filename = f"{add_str}_{f}"
66
  else:
67
+ name, file_ext = os.path.splitext(f)
68
+ new_filename = f"{name}_{add_str}{file_ext}"
 
69
 
70
  new_path = os.path.join(renamed_dir, new_filename)
71
  shutil.copy2(old_path, new_path)
72
 
73
+ # 將重新命名後的檔案打包成原本格式
74
+ output_archive_name = f"processed_{filename}"
75
+ output_archive_path = os.path.join(temp_dir, output_archive_name)
76
 
77
+ if ext == '.zip':
78
+ with zipfile.ZipFile(output_archive_path, 'w', zipfile.ZIP_DEFLATED) as out_zip:
79
+ for root, dirs, files in os.walk(renamed_dir):
80
+ for f in files:
81
+ file_to_zip = os.path.join(root, f)
82
+ out_zip.write(file_to_zip, arcname=f)
83
+ elif ext == '.7z':
84
+ with py7zr.SevenZipFile(output_archive_path, 'w') as out_7z:
85
+ for root, dirs, files in os.walk(renamed_dir):
86
+ for f in files:
87
+ file_to_7z = os.path.join(root, f)
88
+ out_7z.write(file_to_7z, arcname=f)
89
 
90
+ processed_files.append(output_archive_path)
91
 
92
  return processed_files
93
 
94
  # 建立 Gradio 網頁介面
95
  with gr.Blocks(title="壓縮檔內容批次重新命名工具", theme=gr.themes.Soft()) as demo:
96
+ gr.Markdown("## 📦 壓縮檔內容批次重新命名工具 (支援 ZIP 與 7Z)")
97
+ gr.Markdown("上傳 `.zip` 或 `.7z` 檔案後,自訂你想增加的文字與位置。系統處理完畢後會提供相同格式新壓縮檔下載。")
98
 
99
  with gr.Row():
 
100
  with gr.Column(scale=1):
101
  gr.Markdown("### ⚙️ 命名規則設定")
102
  position_radio = gr.Radio(
 
119
  info="需在上方勾選「自訂文字」才會生效"
120
  )
121
 
 
122
  with gr.Column(scale=1):
123
  gr.Markdown("### 📂 檔案上傳與下載")
124
+ # 更新 file_types,讓介面允許 .7z 檔案
125
+ file_input = gr.File(label="上傳壓縮檔 (可多選 ZIP 或 7Z)", file_count="multiple", type="filepath", file_types=[".zip", ".7z"])
126
  submit_btn = gr.Button("🚀 開始處理", variant="primary")
127
  file_output = gr.File(label="下載處理後的新壓縮檔")
128
 
 
129
  submit_btn.click(
130
+ fn=process_archives,
131
  inputs=[file_input, position_radio, options_checkbox, custom_text_input],
132
  outputs=file_output
133
  )