CoolFace
Apppublic

Kims12/bbb

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
0likes
app.py207 linesDownload Raw Back to root
1import os2from datetime import datetime, timedelta3import gradio as gr4 5def simulate_file_naming(name_option, additional_name, add_date, add_time):6    # 고정된 원본 파일명7    original_filename = "sample.jpg"8    original_name, ext = os.path.splitext(original_filename)9    ext = ext.lstrip(".") if ext else "bin"10    11    # 옵션에 따른 파일명 기본 부분 결정12    if name_option == "파일명변경":13        final_base = additional_name.strip() if additional_name.strip() else "파일"14        option_text = f"파일명변경 ({additional_name.strip() if additional_name.strip() else '기본값'})"15    elif name_option == "파일명유지":16        final_base = original_name17        option_text = "파일명유지"18    elif name_option == "파일명유지 + 추가명":19        final_base = original_name + (f"_{additional_name.strip()}" if additional_name.strip() else "")20        option_text = f"파일명유지 + 추가명 ({additional_name.strip() if additional_name.strip() else '없음'})"21    elif name_option == "추가명 + 파일명유지":22        final_base = (f"{additional_name.strip()}_" if additional_name.strip() else "") + original_name23        option_text = f"추가명 + 파일명유지 ({additional_name.strip() if additional_name.strip() else '없음'})"24    else:25        final_base = original_name26        option_text = "미선택"27    28    # 날짜 및 시간 stamp (한국 기준)29    now = datetime.utcnow() + timedelta(hours=9)30    date_str = now.strftime('%Y%m%d') if add_date else ""31    time_str = now.strftime('%H%M%S') if add_time else ""32    timestamp = ""33    additional_info = []34    if add_date:35        additional_info.append("날짜 적용")36        timestamp += f"_{date_str}"37    if add_time:38        additional_info.append("시간 적용")39        timestamp += f"_{time_str}"40    41    # 최종 파일명 구성 (확장자 유지)42    final_file_name = f"{final_base}{timestamp}.{ext}"43    44    # 상세 결과 메시지 구성45    detail_msg = (46        f"원본이름 : {original_filename}\n"47        f"옵션선택 : {option_text}\n"48        f"추가 : {', '.join(additional_info) if additional_info else '없음'}\n"49        f"결과명 : {final_file_name}"50    )51    52    return detail_msg, final_file_name53 54# 코드출력에 표시할 전체 코드 문자열 (헤더는 제거)55code_str = '''56위 선택된 항목부분과 업로드 된 파일명을 기반으로 아래 코드를 활용하여 바로 적용할수 있는 코드로 변경하세요.57파일명을 바꾸는 기능의 코드 외 모두 삭제하세요.58 59import os60import tempfile61from datetime import datetime, timedelta62import gradio as gr63from PIL import Image64def save_file(file_data, final_file_name):65    """66    파일 데이터를 임시 폴더에 저장하고 최종 파일 경로를 반환.67    final_file_name에는 확장자 포함.68    """69    temp_file_path = os.path.join(tempfile.gettempdir(), final_file_name)70    71    # 업로드된 파일이 파일 경로인 경우72    if isinstance(file_data, str) and os.path.exists(file_data):73        with open(file_data, "rb") as f:74            data = f.read()75        with open(temp_file_path, "wb") as f:76            f.write(data)77    # PIL 이미지 객체인 경우78    elif hasattr(file_data, "save"):79        ext = os.path.splitext(final_file_name)[1].lstrip(".")80        pil_format = "JPEG" if ext.lower() == "jpg" else ext.upper()81        file_data.save(temp_file_path, format=pil_format)82    # bytes 데이터인 경우83    elif isinstance(file_data, bytes):84        with open(temp_file_path, "wb") as f:85            f.write(file_data)86    # 문자열 데이터인 경우 (예: 텍스트)87    elif isinstance(file_data, str):88        with open(temp_file_path, "w", encoding="utf-8") as f:89            f.write(file_data)90    else:91        raise ValueError("지원되지 않는 파일 형식입니다.")92    93    return temp_file_path94def process_file(file, name_option, additional_name, add_date, add_time):95    """96    업로드된 파일을 받아 라디오 옵션에 따라 파일명을 재구성한 후 저장합니다.97    98    Parameters:99      file: 업로드된 파일 (gr.File 등, 파일 경로 또는 파일 객체)100      name_option: 라디오 버튼 선택값 (네 가지 옵션 중 하나)101      additional_name: 옵션에 따른 추가 입력(추가명 또는 변경할 파일명)102      add_date: 날짜 적용 여부 (Boolean)103      add_time: 시간 적용 여부 (Boolean)104    105    반환값:106      변경된 파일명을 가진 다운로드 가능한 파일 경로107    """108    if file is None:109        return None110    # 원본 파일명과 확장자 추출111    if isinstance(file, str) and os.path.exists(file):112        original_filename = os.path.basename(file)113    elif hasattr(file, "name"):114        original_filename = os.path.basename(file.name)115    else:116        original_filename = "파일.bin"117        118    original_name, ext = os.path.splitext(original_filename)119    ext = ext.lstrip(".") if ext else "bin"120    121    # 라디오 옵션에 따라 최종 기본 파일명 결정122    if name_option == "파일명변경":123        # 입력된 새 파일명 사용 (없으면 기본값 "파일")124        final_base = additional_name.strip() if additional_name.strip() else "파일"125    elif name_option == "파일명유지":126        final_base = original_name127    elif name_option == "파일명유지 + 추가명":128        final_base = original_name + (f"_{additional_name.strip()}" if additional_name.strip() else "")129    elif name_option == "추가명 + 파일명유지":130        final_base = (f"{additional_name.strip()}_" if additional_name.strip() else "") + original_name131    else:132        final_base = original_name133    # 날짜 및 시간 stamp (한국 기준)134    now = datetime.utcnow() + timedelta(hours=9)135    date_str = now.strftime('%Y%m%d') if add_date else ""136    time_str = now.strftime('%H%M%S') if add_time else ""137    timestamp = ""138    if date_str and time_str:139        timestamp = f"_{date_str}_{time_str}"140    elif date_str:141        timestamp = f"_{date_str}"142    elif time_str:143        timestamp = f"_{time_str}"144    145    # 최종 파일명 구성 (접두사 제거)146    final_file_name = f"{final_base}{timestamp}.{ext}"147    148    return save_file(file, final_file_name)149iface = gr.Interface(150    fn=process_file,151    inputs=[152        gr.File(label="파일 업로드"),153        gr.Radio(154            choices=["파일명변경", "파일명유지", "파일명유지 + 추가명", "추가명 + 파일명유지"],155            label="파일명 옵션"156        ),157        gr.Text(label="추가명/변경 파일명 입력", placeholder="옵션에 따라 입력하세요"),158        gr.Checkbox(label="날짜 적용", value=True),159        gr.Checkbox(label="시간 적용", value=True)160    ],161    outputs=gr.File(label="다운로드 파일"),162    title="파일명 옵션에 따른 파일명 변경 및 다운로드",163    description=(164        "업로드된 파일의 파일명을 아래 옵션에 따라 변경합니다.\n"165        "옵션1(파일명변경): 입력한 이름으로 파일명 변경\n"166        "옵션2(파일명유지): 원본 파일명 유지\n"167        "옵션3(파일명유지 + 추가명): 원본 파일명 뒤에 추가명 부착\n"168        "옵션4(추가명 + 파일명유지): 추가명을 원본 파일명 앞에 부착\n"169        "날짜/시간 체크 시 해당 정보가 파일명 뒤에 추가됩니다."170    )171)172if __name__ == "__main__":173    iface.launch()'''174 175def update_all(name_option, additional_name, add_date, add_time):176    detail_msg, final_file_name = simulate_file_naming(name_option, additional_name, add_date, add_time)177    # 코드출력 영역 최상단에 "[파일명 변경 코드예시]"와 한 칸 띄운 후 선택예시 결과(detail_msg)와 전체 코드 출력178    code_result = f"[파일명 변경 코드예시]\n\n{detail_msg}\n\n{code_str}"179    return final_file_name, code_result180 181with gr.Blocks() as demo:182    with gr.Group():183        gr.Markdown("### 원본 파일명: sample.jpg")184        with gr.Row():185            name_option = gr.Radio(186                choices=["파일명변경", "파일명유지", "파일명유지 + 추가명", "추가명 + 파일명유지"],187                label="파일명 옵션",188                value="파일명변경"189            )190            additional_name = gr.Text(191                label="추가명/변경 파일명 입력", 192                placeholder="옵션에 따라 입력하세요"193            )194        with gr.Row():195            add_date = gr.Checkbox(label="날짜 적용", value=True)196            add_time = gr.Checkbox(label="시간 적용", value=True)197        with gr.Row():198            final_filename_output = gr.Text(label="파일명결과", lines=2)199        with gr.Row():200            code_output = gr.Text(label="코드출력", lines=20)201    202    inputs = [name_option, additional_name, add_date, add_time]203    outputs = [final_filename_output, code_output]204    for comp in inputs:205        comp.change(update_all, inputs=inputs, outputs=outputs)206    207demo.launch()