Spaces:
Running
Running
Update app.py
Browse files22 unmodified lines2324252627282930313233343 unmodified lines3839404142434445464748497 unmodified lines575859606162636465666768697071727374757625 unmodified lines10210310410510610710824 unmodified lines13313413513613713813916 unmodified lines1561571581591601611621631641651661671681691701711721731741759 unmodified lines18518618718818919019119219322 unmodified lines21621721821922022122222322422522622722822923023123223322 unmodified linesdict_path = "custom_dict.json"# 시작할 때 사전 파일이 없으면 새로 생성 (에러 방지)if not os.path.exists(dict_path):with open(dict_path, "w", encoding="utf-8") as f:json.dump({"items":[], "meta": {"count": 0}}, f)# 클라우드에 영구 백업된 사전을 자동으로 불러오는 함수def load_dict():flat_dict = {}try:3 unmodified linesfor item in data.get("items",[]):if len(item) == 2:flat_dict[item[0]] = item[1]except Exception as e:print(f"사전 로딩 에러: {e}")return flat_dict# ☁️ 허깅페이스 클라우드에 사전을 영구적으로 덮어쓰는(백업) 함수def auto_backup_to_space():space_id = os.environ.get("SPACE_ID")hf_token = os.environ.get("HF_TOKEN")7 unmodified linesrepo_type="space",token=hf_token)return Trueexcept Exception as e:print(f"자동 백업 에러: {e}")return Falsereturn False# 텍스트 변환 핵심 로직 (사용자 단어 절대 보호)def process_text(input_text):if not input_text or not input_text.strip():return "", "", "입력 글자 수: 0자"char_count = f"입력 글자 수: {len(input_text)}자"# 변환할 때마다 항상 최신 사전을 불러옴flat_dict = load_dict()if not flat_dict:25 unmodified linesmatched_word = match.group()parts.append(flat_dict[matched_word])last_end = endtail = input_text[last_end:]24 unmodified linesdef clear_all():return "", "", "", "입력 글자 수: 0자"# 단어 추가 + 실시간 변환 + 클라우드 자동 백업 실행def add_and_update(word, pronun, current_input):if not word or not pronun:return "⚠️ 단어와 발음을 모두 입력하세요.", gr.update(), gr.update(), gr.update()16 unmodified linestry:with open(dict_path, "w", encoding="utf-8") as f:json.dump(j_struct, f, ensure_ascii=False, indent=2)# ★ 등록하신 HF_TOKEN을 이용해 클라우드에 영구 백업 실행 ★is_synced = auto_backup_to_space()status_msg = f"✅ '{word}' -> '{pronun}' 저장 완료"if is_synced:status_msg += " (☁️ 클라우드 영구 저장 완료! 리스타트해도 유지됩니다)"else:status_msg += " (※ 백업 실패: 토큰 설정을 다시 확인해주세요)"except Exception as e:status_msg = f"❌ 저장 실패: {e}"# 즉시 화면 갱신if current_input and current_input.strip():final_text, html_output, char_count = process_text(current_input)return status_msg, final_text, html_output, char_count9 unmodified linesreturn "✅ 수동 백업 복구 완료!"return "⚠️ 파일이 없습니다."# UI 화면with gr.Blocks(theme="default") as iface:gr.Markdown("## 🎙️ 나만의 TTS 전처리 변환기 (☁️ 클라우드 자동 백업 활성화)")with gr.Tabs():with gr.Tab("🎙️ 메인 화면"):22 unmodified lineswith gr.Row():nw = gr.Textbox(label="기존 단어 또는 문장")np = gr.Textbox(label="원하는 발음")btn_add = gr.Button("💾 사전에 추가", variant="primary")status = gr.Textbox(label="저장 상태 결과창", interactive=False)btn_add.click(fn=add_and_update,inputs=[nw, np, input_text],outputs=[status, output_text, output_html, char_count],api_name=False)with gr.Tab("📥 수동 백업/복구 (비상용)"):gr.Markdown("💡 클라우드 자동 저장이 켜져 있으므로 이 탭은 비상시에만 사용하시면 됩니다.")dl_btn = gr.DownloadButton("📥 1. 현재 사전 백업하기 (PC 다운로드)")dl_btn.click(fn=get_file, outputs=[dl_btn], api_name=False)22 unmodified lines232425262728293031323 unmodified lines3637383940414243444546477 unmodified lines5556575859606162636465666768697025 unmodified lines9697989910010124 unmodified lines12612712812913013113216 unmodified lines1491501511521531541551561571581591601619 unmodified lines17117217317417517617717822 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222322 unmodified linesdict_path = "custom_dict.json"if not os.path.exists(dict_path):with open(dict_path, "w", encoding="utf-8") as f:json.dump({"items":[], "meta": {"count": 0}}, f)def load_dict():flat_dict = {}try:3 unmodified linesfor item in data.get("items",[]):if len(item) == 2:flat_dict[item[0]] = item[1]except:passreturn flat_dict# 클라우드 수동 백업 함수 (버튼 누를 때만 작동)def backup_to_space():space_id = os.environ.get("SPACE_ID")hf_token = os.environ.get("HF_TOKEN")7 unmodified linesrepo_type="space",token=hf_token)return "☁️ 클라우드 영구 저장 완료! (※ 잠시 후 서버가 백업을 위해 자동으로 새로고침 될 수 있습니다)"except Exception as e:return f"❌ 백업 실패: {e}"return "⚠️ HF_TOKEN이 설정되지 않아 클라우드 저장을 할 수 없습니다."def process_text(input_text):if not input_text or not input_text.strip():return "", "", "입력 글자 수: 0자"char_count = f"입력 글자 수: {len(input_text)}자"flat_dict = load_dict()if not flat_dict:25 unmodified linesmatched_word = match.group()parts.append(flat_dict[matched_word])last_end = endtail = input_text[last_end:]24 unmodified linesdef clear_all():return "", "", "", "입력 글자 수: 0자"# 단어 추가 + 실시간 변환 (재시작 안 됨!)def add_and_update(word, pronun, current_input):if not word or not pronun:return "⚠️ 단어와 발음을 모두 입력하세요.", gr.update(), gr.update(), gr.update()16 unmodified linestry:with open(dict_path, "w", encoding="utf-8") as f:json.dump(j_struct, f, ensure_ascii=False, indent=2)# 클라우드 자동 저장을 빼버림 (대본 날아감 방지)status_msg = f"✅ '{word}' -> '{pronun}' 임시 적용 완료! (영구 저장은 아래 ☁️ 버튼을 누르세요)"except Exception as e:status_msg = f"❌ 저장 실패: {e}"if current_input and current_input.strip():final_text, html_output, char_count = process_text(current_input)return status_msg, final_text, html_output, char_count9 unmodified linesreturn "✅ 수동 백업 복구 완료!"return "⚠️ 파일이 없습니다."with gr.Blocks(theme="default") as iface:gr.Markdown("## 🎙️ 나만의 TTS 전처리 변환기 (재시작 방지 최적화)")with gr.Tabs():with gr.Tab("🎙️ 메인 화면"):22 unmodified lineswith gr.Row():nw = gr.Textbox(label="기존 단어 또는 문장")np = gr.Textbox(label="원하는 발음")btn_add = gr.Button("💾 사전에 추가 (대본 유지됨)", variant="primary")status = gr.Textbox(label="저장 상태 결과창", interactive=False)# 단어 추가 시 재시작 없이 화면만 갱신btn_add.click(fn=add_and_update,inputs=[nw, np, input_text],outputs=[status, output_text, output_html, char_count],api_name=False)gr.Markdown("---")btn_sync = gr.Button("☁️ 작업이 끝나면 여기를 눌러 클라우드에 영구 백업하세요 (서버 새로고침 됨)")btn_sync.click(fn=backup_to_space, outputs=[status], api_name=False)with gr.Tab("📥 수동 백업/복구 (비상용)"):dl_btn = gr.DownloadButton("📥 1. 현재 사전 백업하기 (PC 다운로드)")dl_btn.click(fn=get_file, outputs=[dl_btn], api_name=False)
app.py+18-28