Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778791 unmodified lineimport osimport yamlimport shutil# 确保 papers 文件夹存在os.makedirs("papers", exist_ok=True)def save_pdf(file):if file is None:return "Please upload a PDF file."# 获取文件名并保存到 papers 文件夹file_name = os.path.basename(file.name)file_path = os.path.join("papers", file_name)shutil.copy(file.name, file_path)# --- 调试打印逻辑 ---print(f"\n[DEBUG] 正在检查 papers 文件夹内容...")files_in_dir = os.listdir("papers")print(f"[DEBUG] 当前 papers 目录下的文件列表: {files_in_dir}")# ------------------return f"File '{file_name}' saved successfully. Total files: {len(files_in_dir)}"def save_api_key(api_key):if not api_key:return "API Key cannot be empty."config_path = "config.yaml"try:# 如果文件不存在,初始化一个空字典if not os.path.exists(config_path):config = {}else:# 读取现有的 yaml 文件with open(config_path, "r", encoding="utf-8") as f:config = yaml.safe_load(f) or {}# 确保 api_keys 字典存在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)# --- 调试打印逻辑 ---print(f"\n[DEBUG] 正在验证 {config_path} 内容...")with open(config_path, "r", encoding="utf-8") as f:content = f.read()print(f"[DEBUG] 当前 config.yaml 内容:\n{content}")# ------------------return "Gemini API Key updated successfully in config.yaml!"except Exception as e:return f"Error saving API Key: {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", placeholder="Paste your API key here...")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__":# 在 HF Spaces 运行通常只需要 launch(),不需要手动指定端口demo.launch()1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293941 unmodified lineimport osimport yamlimport 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()
app.py+66-51