Saditiya's picture
Update app.py
7f8fc26 verified
import gradio as gr
import pandas as pd
import shutil
import tempfile
from pathlib import Path
from zipfile import ZipFile
def rename_and_zip(files, excel_file):
if not excel_file:
return "❌ Mohon unggah file Excel dengan kolom A (nama lama) dan kolom B (nama baru)."
try:
# Baca 2 kolom Excel, tanpa header
df = pd.read_excel(excel_file.name, usecols=[0, 1], header=None)
except Exception as e:
return f"❌ Gagal membaca Excel: {e}"
df.columns = ["NamaLama", "NamaBaru"]
# Buat dictionary mapping nama lama -> nama baru
mapping = {str(row["NamaLama"]): str(row["NamaBaru"]) for _, row in df.iterrows()}
temp_dir = tempfile.mkdtemp()
renamed_dir = Path(temp_dir) / "renamed_files"
renamed_dir.mkdir(exist_ok=True)
for file in files:
original_path = Path(file.name)
ext = original_path.suffix
nama_file_tanpa_ext = original_path.stem # nama asli tanpa ekstensi
if nama_file_tanpa_ext in mapping:
new_name = mapping[nama_file_tanpa_ext] + ext
else:
# jika tidak cocok, tetap nama asli
new_name = original_path.name
new_path = renamed_dir / new_name
shutil.copy(file.name, new_path)
# Buat zip
zip_path = Path(temp_dir) / "hasil_rename.zip"
with ZipFile(zip_path, "w") as zipf:
for f in renamed_dir.iterdir():
zipf.write(f, arcname=f.name)
return str(zip_path)
with gr.Blocks() as demo:
gr.Markdown("## Rename File berdasarkan Kolom A ke Kolom B di Excel, lalu unduh ZIP")
with gr.Row():
file_input = gr.File(file_count="multiple", label="πŸ“ Upload file apa saja")
excel_input = gr.File(file_types=[".xls", ".xlsx"], label="πŸ“„ Upload Excel (Kolom A: nama lama tanpa ekstensi, Kolom B: nama baru)")
rename_button = gr.Button("πŸ”„ Proses & Rename ke ZIP")
zip_output = gr.File(label="πŸ“¦ Unduh File ZIP")
rename_button.click(rename_and_zip, inputs=[file_input, excel_input], outputs=zip_output)
demo.launch()