Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293943 unmodified linesimport shutilimport sys# 基础路径配置BASE_DIR = os.path.dirname(os.path.abspath(__file__))PAPERS_DIR = os.path.join(BASE_DIR, "papers")CONFIG_PATH = os.path.join(BASE_DIR, "config.yaml")# 确保文件夹存在os.makedirs(PAPERS_DIR, exist_ok=True)def logger(message):"""强制刷新日志,确保在 HF Logs 中可见"""print(f">>> [APP LOG]: {message}", file=sys.stderr, flush=True)def save_pdf(file):if file is None:return "❌ Please upload a PDF file."try:file_name = os.path.basename(file.name)file_path = os.path.join(PAPERS_DIR, file_name)# 使用 shutil 复制shutil.copy(file.name, file_path)# 验证文件是否存在并打印日志if os.path.exists(file_path):existing_files = os.listdir(PAPERS_DIR)logger(f"Successfully saved: {file_name}")logger(f"Current files in 'papers/': {existing_files}")return f"✅ File '{file_name}' saved. Total: {len(existing_files)} files."else:return "❌ Failed to verify file on disk."except Exception as e:logger(f"Error saving PDF: {str(e)}")return f"❌ Error: {str(e)}"def save_api_key(api_key):if not api_key or len(api_key) < 10:return "❌ Invalid API Key format."try:# 读取或初始化配置config = {}if os.path.exists(CONFIG_PATH):with open(CONFIG_PATH, "r", encoding="utf-8") as f:config = yaml.safe_load(f) or {}# 更新配置结构if "api_keys" not in config:config["api_keys"] = {}config["api_keys"]["gemini_api_key"] = api_key# 写入文件with open(CONFIG_PATH, "w", encoding="utf-8") as f:yaml.dump(config, f, allow_unicode=True, default_flow_style=False)# 立即读取验证并打印with open(CONFIG_PATH, "r", encoding="utf-8") as f:verify_content = f.read()logger("Config file updated. Current content (REDACTED):")# 出于安全考虑,日志里只打印 key 的前几位logger(verify_content.replace(api_key, api_key[:5] + "******"))return "✅ Gemini API Key updated and verified in config.yaml!"except Exception as e:logger(f"Error saving config: {str(e)}")return f"❌ Error: {str(e)}"# --- UI 界面 ---with gr.Blocks() as demo:gr.Markdown("# 📄 AI Paper Assistant")with gr.Tab("1. System Setup"):gr.Markdown("### 🔑 API Configuration\nConfigure your keys before processing PDFs.")api_input = gr.Textbox(label="Gemini API Key", type="password", placeholder="sk-...")api_btn = gr.Button("Update Config")api_status = gr.Textbox(label="Config Status")api_btn.click(save_api_key, inputs=api_input, outputs=api_status)with gr.Tab("2. Upload & Process"):gr.Markdown("### 📁 PDF Upload\nUpload papers to the server's local storage.")pdf_input = gr.File(label="Choose PDF", file_types=[".pdf"])pdf_btn = gr.Button("Save to Papers Folder")pdf_status = gr.Textbox(label="Upload Status")pdf_btn.click(save_pdf, inputs=pdf_input, outputs=pdf_status)if __name__ == "__main__":logger("Application starting...")demo.launch()3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384853 unmodified linesimport shutilimport sys# 强制在启动时打印 START,并直接输出到 stderr 确保可见print("==== [SYSTEM] APP STARTING... ====", file=sys.stderr, flush=True)# 确保 papers 文件夹存在os.makedirs("papers", exist_ok=True)def debug_log(message):"""自定义调试函数,确保内容立即出现在日志中"""print(f"[DEBUG] {message}", file=sys.stderr, flush=True)def save_pdf(file):if file is None:return "Please upload a PDF file."debug_log(f"Received file: {file.name}")# 获取文件名并保存file_name = os.path.basename(file.name)file_path = os.path.join("papers", file_name)shutil.copy(file.name, file_path)# 打印文件夹下的所有文件all_files = os.listdir("papers")debug_log(f"File saved to {file_path}")debug_log(f"Current files in 'papers/': {all_files}")return f"File '{file_name}' saved. Total files in folder: {len(all_files)}"def save_api_key(api_key):if not api_key:return "API Key cannot be empty."config_path = "config.yaml"debug_log("Attempting to save API Key...")try:config = {}if os.path.exists(config_path):with open(config_path, "r", encoding="utf-8") as f:config = yaml.safe_load(f) or {}if "api_keys" not in config:config["api_keys"] = {}config["api_keys"]["gemini_api_key"] = api_keywith open(config_path, "w", encoding="utf-8") as f:yaml.dump(config, f, allow_unicode=True, default_flow_style=False)# 验证并打印 config 内容 (脱敏处理)with open(config_path, "r", encoding="utf-8") as f:current_config = f.read()# 打印前20个字符确认文件结构,不打印完整 keydebug_log(f"Config updated. Content preview: {current_config[:20]}...")return "Gemini API Key updated successfully!"except Exception as e:debug_log(f"ERROR: {str(e)}")return f"Error: {str(e)}"with gr.Blocks(title="PDF Uploader & Config") as demo:gr.Markdown("# PDF and API Configuration")with gr.Tab("Upload PDF"):file_input = gr.File(label="Upload your PDF", file_types=[".pdf"])upload_btn = gr.Button("Save PDF")upload_output = gr.Textbox(label="Status")upload_btn.click(save_pdf, inputs=file_input, outputs=upload_output)with gr.Tab("Gemini Configuration"):key_input = gr.Textbox(label="Enter Gemini API Key", type="password")key_btn = gr.Button("Save API Key")key_output = gr.Textbox(label="Status")key_btn.click(save_api_key, inputs=key_input, outputs=key_output)if __name__ == "__main__":debug_log("Gradio Interface launching...")# HF Spaces 环境下 server_name 和 port 通常由平台处理,简单 launch 即可demo.launch()
app.py+52-61