Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041421 unmodified line44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889904 unmodified linesimport sysfrom datetime import datetime# 强制刷新打印(最后一次尝试后台日志)print("!!! CRITICAL STARTUP CHECK !!!", file=sys.stderr, flush=True)# 初始化环境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 get_debug_info():"""获取当前服务器文件状态的快照"""now = datetime.now().strftime("%H:%M:%S")files = os.listdir(PAPERS_DIR) if os.path.exists(PAPERS_DIR) else "Directory missing"config_content = "Not found"if os.path.exists(CONFIG_PATH):with open(CONFIG_PATH, "r", encoding="utf-8") as f:config_content = f.read()return f"[{now}] 📁 Files in papers/: {files}\n\n[{now}] 📄 config.yaml content:\n{config_content}"def save_pdf(file):if file is None:return "Please upload a PDF.", get_debug_info()file_path = os.path.join(PAPERS_DIR, os.path.basename(file.name))shutil.copy(file.name, file_path)return f"✅ Saved {os.path.basename(file.name)}", get_debug_info()def save_api_key(api_key):if not api_key:return "API Key is empty.", get_debug_info()try:config = {}1 unmodified linewith 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)return "✅ API Key saved!", get_debug_info()except Exception as e:return f"❌ Error: {str(e)}", get_debug_info()# --- UI 界面 ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🛠️ Space Files Debugger")with gr.Row():with gr.Column(scale=2):with gr.Tab("1. Upload PDF"):pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])pdf_btn = gr.Button("Save PDF")pdf_msg = gr.Textbox(label="Status")with gr.Tab("2. Config"):key_input = gr.Textbox(label="Gemini API Key", type="password")key_btn = gr.Button("Save Key")key_msg = gr.Textbox(label="Status")# 右侧调试面板:实时显示服务器文件系统状态with gr.Column(scale=1):gr.Markdown("### 🔍 System Real-time Monitor")debug_view = gr.Textbox(label="Server File Explorer",value=get_debug_info(),lines=15,interactive=False)refresh_btn = gr.Button("🔄 Force Refresh View")# 绑定逻辑:每次操作都更新右侧的调试面板pdf_btn.click(save_pdf, inputs=pdf_input, outputs=[pdf_msg, debug_view])key_btn.click(save_api_key, inputs=key_input, outputs=[key_msg, debug_view])refresh_btn.click(get_debug_info, outputs=debug_view)if __name__ == "__main__":demo.launch()4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445461 unmodified line484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181194 unmodified linesimport sysfrom datetime import datetime# 初始化环境路径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 get_debug_info():"""读取服务器文件系统状态,用于实时监控"""now = datetime.now().strftime("%H:%M:%S")files = os.listdir(PAPERS_DIR) if os.path.exists(PAPERS_DIR) else "Directory missing"config_content = "Not found"if os.path.exists(CONFIG_PATH):try:with open(CONFIG_PATH, "r", encoding="utf-8") as f:config_content = f.read()except Exception:config_content = "Error reading config"return f"[{now}] 📁 papers/ 文件夹下的文件:\n{files}\n\n[{now}] 📄 config.yaml 完整内容:\n{config_content}"def save_pdf(file):if file is None:return "❌ 请先选择一个 PDF 文件", get_debug_info()try:file_name = os.path.basename(file.name)file_path = os.path.join(PAPERS_DIR, file_name)shutil.copy(file.name, file_path)return f"✅ 成功保存文件: {file_name}", get_debug_info()except Exception as e:return f"❌ 保存 PDF 出错: {str(e)}", get_debug_info()def save_api_key(api_key):if not api_key:return "❌ API Key 不能为空", get_debug_info()try:config = {}1 unmodified linewith 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)return "✅ API Key 已成功写入 config.yaml", get_debug_info()except Exception as e:return f"❌ 保存 Key 出错: {str(e)}", get_debug_info()# --- 构建单页 UI ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 📑 PDF 助手管理后台")with gr.Row():# 左侧操作区with gr.Column(scale=2):# 第一部分:API 配置with gr.Group():gr.Markdown("### 1. 密钥配置")key_input = gr.Textbox(label="Gemini API Key",type="password",placeholder="在此输入您的 API Key...")key_btn = gr.Button("保存配置", variant="primary")key_status = gr.Textbox(label="配置状态", interactive=False)gr.Markdown("---") # 分割线# 第二部分:PDF 上传with gr.Group():gr.Markdown("### 2. 论文上传")pdf_input = gr.File(label="选择 PDF 文件", file_types=[".pdf"])pdf_btn = gr.Button("保存到 papers 文件夹", variant="primary")pdf_status = gr.Textbox(label="上传状态", interactive=False)# 右侧调试监控区with gr.Column(scale=1):gr.Markdown("### 🔍 实时系统监控")debug_view = gr.Textbox(label="服务器文件状态 (每操作一次即自动更新)",value=get_debug_info(),lines=20,interactive=False)refresh_btn = gr.Button("🔄 手动刷新状态")# 绑定事件逻辑key_btn.click(fn=save_api_key,inputs=key_input,outputs=[key_status, debug_view])pdf_btn.click(fn=save_pdf,inputs=pdf_input,outputs=[pdf_status, debug_view])refresh_btn.click(fn=get_debug_info,outputs=debug_view)if __name__ == "__main__":demo.launch()
app.py+67-38