import os from datetime import datetime, timedelta import gradio as gr def simulate_file_naming(name_option, additional_name, add_date, add_time): # 고정된 원본 파일명 original_filename = "sample.jpg" original_name, ext = os.path.splitext(original_filename) ext = ext.lstrip(".") if ext else "bin" # 옵션에 따른 파일명 기본 부분 결정 if name_option == "파일명변경": final_base = additional_name.strip() if additional_name.strip() else "파일" option_text = f"파일명변경 ({additional_name.strip() if additional_name.strip() else '기본값'})" elif name_option == "파일명유지": final_base = original_name option_text = "파일명유지" elif name_option == "파일명유지 + 추가명": final_base = original_name + (f"_{additional_name.strip()}" if additional_name.strip() else "") option_text = f"파일명유지 + 추가명 ({additional_name.strip() if additional_name.strip() else '없음'})" elif name_option == "추가명 + 파일명유지": final_base = (f"{additional_name.strip()}_" if additional_name.strip() else "") + original_name option_text = f"추가명 + 파일명유지 ({additional_name.strip() if additional_name.strip() else '없음'})" else: final_base = original_name option_text = "미선택" # 날짜 및 시간 stamp (한국 기준) now = datetime.utcnow() + timedelta(hours=9) date_str = now.strftime('%Y%m%d') if add_date else "" time_str = now.strftime('%H%M%S') if add_time else "" timestamp = "" additional_info = [] if add_date: additional_info.append("날짜 적용") timestamp += f"_{date_str}" if add_time: additional_info.append("시간 적용") timestamp += f"_{time_str}" # 최종 파일명 구성 (확장자 유지) final_file_name = f"{final_base}{timestamp}.{ext}" # 상세 결과 메시지 구성 detail_msg = ( f"원본이름 : {original_filename}\n" f"옵션선택 : {option_text}\n" f"추가 : {', '.join(additional_info) if additional_info else '없음'}\n" f"결과명 : {final_file_name}" ) return detail_msg, final_file_name # 코드출력에 표시할 전체 코드 문자열 (헤더는 제거) code_str = ''' 위 선택된 항목부분과 업로드 된 파일명을 기반으로 아래 코드를 활용하여 바로 적용할수 있는 코드로 변경하세요. 파일명을 바꾸는 기능의 코드 외 모두 삭제하세요. import os import tempfile from datetime import datetime, timedelta import gradio as gr from PIL import Image def save_file(file_data, final_file_name): """ 파일 데이터를 임시 폴더에 저장하고 최종 파일 경로를 반환. final_file_name에는 확장자 포함. """ temp_file_path = os.path.join(tempfile.gettempdir(), final_file_name) # 업로드된 파일이 파일 경로인 경우 if isinstance(file_data, str) and os.path.exists(file_data): with open(file_data, "rb") as f: data = f.read() with open(temp_file_path, "wb") as f: f.write(data) # PIL 이미지 객체인 경우 elif hasattr(file_data, "save"): ext = os.path.splitext(final_file_name)[1].lstrip(".") pil_format = "JPEG" if ext.lower() == "jpg" else ext.upper() file_data.save(temp_file_path, format=pil_format) # bytes 데이터인 경우 elif isinstance(file_data, bytes): with open(temp_file_path, "wb") as f: f.write(file_data) # 문자열 데이터인 경우 (예: 텍스트) elif isinstance(file_data, str): with open(temp_file_path, "w", encoding="utf-8") as f: f.write(file_data) else: raise ValueError("지원되지 않는 파일 형식입니다.") return temp_file_path def process_file(file, name_option, additional_name, add_date, add_time): """ 업로드된 파일을 받아 라디오 옵션에 따라 파일명을 재구성한 후 저장합니다. Parameters: file: 업로드된 파일 (gr.File 등, 파일 경로 또는 파일 객체) name_option: 라디오 버튼 선택값 (네 가지 옵션 중 하나) additional_name: 옵션에 따른 추가 입력(추가명 또는 변경할 파일명) add_date: 날짜 적용 여부 (Boolean) add_time: 시간 적용 여부 (Boolean) 반환값: 변경된 파일명을 가진 다운로드 가능한 파일 경로 """ if file is None: return None # 원본 파일명과 확장자 추출 if isinstance(file, str) and os.path.exists(file): original_filename = os.path.basename(file) elif hasattr(file, "name"): original_filename = os.path.basename(file.name) else: original_filename = "파일.bin" original_name, ext = os.path.splitext(original_filename) ext = ext.lstrip(".") if ext else "bin" # 라디오 옵션에 따라 최종 기본 파일명 결정 if name_option == "파일명변경": # 입력된 새 파일명 사용 (없으면 기본값 "파일") final_base = additional_name.strip() if additional_name.strip() else "파일" elif name_option == "파일명유지": final_base = original_name elif name_option == "파일명유지 + 추가명": final_base = original_name + (f"_{additional_name.strip()}" if additional_name.strip() else "") elif name_option == "추가명 + 파일명유지": final_base = (f"{additional_name.strip()}_" if additional_name.strip() else "") + original_name else: final_base = original_name # 날짜 및 시간 stamp (한국 기준) now = datetime.utcnow() + timedelta(hours=9) date_str = now.strftime('%Y%m%d') if add_date else "" time_str = now.strftime('%H%M%S') if add_time else "" timestamp = "" if date_str and time_str: timestamp = f"_{date_str}_{time_str}" elif date_str: timestamp = f"_{date_str}" elif time_str: timestamp = f"_{time_str}" # 최종 파일명 구성 (접두사 제거) final_file_name = f"{final_base}{timestamp}.{ext}" return save_file(file, final_file_name) iface = gr.Interface( fn=process_file, inputs=[ gr.File(label="파일 업로드"), gr.Radio( choices=["파일명변경", "파일명유지", "파일명유지 + 추가명", "추가명 + 파일명유지"], label="파일명 옵션" ), gr.Text(label="추가명/변경 파일명 입력", placeholder="옵션에 따라 입력하세요"), gr.Checkbox(label="날짜 적용", value=True), gr.Checkbox(label="시간 적용", value=True) ], outputs=gr.File(label="다운로드 파일"), title="파일명 옵션에 따른 파일명 변경 및 다운로드", description=( "업로드된 파일의 파일명을 아래 옵션에 따라 변경합니다.\n" "옵션1(파일명변경): 입력한 이름으로 파일명 변경\n" "옵션2(파일명유지): 원본 파일명 유지\n" "옵션3(파일명유지 + 추가명): 원본 파일명 뒤에 추가명 부착\n" "옵션4(추가명 + 파일명유지): 추가명을 원본 파일명 앞에 부착\n" "날짜/시간 체크 시 해당 정보가 파일명 뒤에 추가됩니다." ) ) if __name__ == "__main__": iface.launch()''' def update_all(name_option, additional_name, add_date, add_time): detail_msg, final_file_name = simulate_file_naming(name_option, additional_name, add_date, add_time) # 코드출력 영역 최상단에 "[파일명 변경 코드예시]"와 한 칸 띄운 후 선택예시 결과(detail_msg)와 전체 코드 출력 code_result = f"[파일명 변경 코드예시]\n\n{detail_msg}\n\n{code_str}" return final_file_name, code_result with gr.Blocks() as demo: with gr.Group(): gr.Markdown("### 원본 파일명: sample.jpg") with gr.Row(): name_option = gr.Radio( choices=["파일명변경", "파일명유지", "파일명유지 + 추가명", "추가명 + 파일명유지"], label="파일명 옵션", value="파일명변경" ) additional_name = gr.Text( label="추가명/변경 파일명 입력", placeholder="옵션에 따라 입력하세요" ) with gr.Row(): add_date = gr.Checkbox(label="날짜 적용", value=True) add_time = gr.Checkbox(label="시간 적용", value=True) with gr.Row(): final_filename_output = gr.Text(label="파일명결과", lines=2) with gr.Row(): code_output = gr.Text(label="코드출력", lines=20) inputs = [name_option, additional_name, add_date, add_time] outputs = [final_filename_output, code_output] for comp in inputs: comp.change(update_all, inputs=inputs, outputs=outputs) demo.launch()