Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines45678910789121310111215161713141516171821192023242526272829303132333435363738394021222324252627282930313233343543443637383940414247434950444546475348495051525859535455626364656667565758596061696263717264656674757667686978798081828370717273747585868788899076777879808182938384853 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")# 强制在启动时打印 START,并直接输出到 stderr 确保可见print("==== [SYSTEM] APP STARTING... ====", file=sys.stderr, flush=True)
# 确保文件夹存在os.makedirs(PAPERS_DIR, exist_ok=True)# 确保 papers 文件夹存在os.makedirs("papers", exist_ok=True)
def logger(message): """强制刷新日志,确保在 HF Logs 中可见""" print(f">>> [APP LOG]: {message}", file=sys.stderr, flush=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." 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)}" 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 or len(api_key) < 10: return "❌ Invalid API Key format." 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: 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: 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] + "******")) # 验证并打印 config 内容 (脱敏处理) with open(config_path, "r", encoding="utf-8") as f: current_config = f.read() # 打印前20个字符确认文件结构,不打印完整 key debug_log(f"Config updated. Content preview: {current_config[:20]}...") return "✅ Gemini API Key updated and verified in config.yaml!" return "Gemini API Key updated successfully!" except Exception as e: logger(f"Error saving config: {str(e)}") return f"❌ Error: {str(e)}" debug_log(f"ERROR: {str(e)}") return f"Error: {str(e)}"
# --- UI 界面 ---with gr.Blocks() as demo: gr.Markdown("# 📄 AI Paper Assistant")with gr.Blocks(title="PDF Uploader & Config") as demo: gr.Markdown("# PDF and API Configuration") 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("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("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) 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__": logger("Application starting...") debug_log("Gradio Interface launching...") # HF Spaces 环境下 server_name 和 port 通常由平台处理,简单 launch 即可 demo.launch()app.py+52-61