snym04 commited on
Commit
57c8b57
·
verified ·
1 Parent(s): e41af69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -61
app.py CHANGED
@@ -4,91 +4,82 @@ import yaml
4
  import shutil
5
  import sys
6
 
7
- # 基础路径配置
8
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
9
- PAPERS_DIR = os.path.join(BASE_DIR, "papers")
10
- CONFIG_PATH = os.path.join(BASE_DIR, "config.yaml")
11
 
12
- # 确保文件夹存在
13
- os.makedirs(PAPERS_DIR, exist_ok=True)
14
 
15
- def logger(message):
16
- """强制刷新日志,确保在 HF Logs 可见"""
17
- print(f">>> [APP LOG]: {message}", file=sys.stderr, flush=True)
18
 
19
  def save_pdf(file):
20
  if file is None:
21
- return "Please upload a PDF file."
22
 
23
- try:
24
- file_name = os.path.basename(file.name)
25
- file_path = os.path.join(PAPERS_DIR, file_name)
26
-
27
- # 使用 shutil 复制
28
- shutil.copy(file.name, file_path)
29
-
30
- # 验证文件是否存在并打印日志
31
- if os.path.exists(file_path):
32
- existing_files = os.listdir(PAPERS_DIR)
33
- logger(f"Successfully saved: {file_name}")
34
- logger(f"Current files in 'papers/': {existing_files}")
35
- return f"File '{file_name}' saved. Total: {len(existing_files)} files."
36
- else:
37
- return "❌ Failed to verify file on disk."
38
- except Exception as e:
39
- logger(f"Error saving PDF: {str(e)}")
40
- return f"❌ Error: {str(e)}"
41
 
42
  def save_api_key(api_key):
43
- if not api_key or len(api_key) < 10:
44
- return "❌ Invalid API Key format."
 
 
 
45
 
46
  try:
47
- # 读取或初始化配置
48
  config = {}
49
- if os.path.exists(CONFIG_PATH):
50
- with open(CONFIG_PATH, "r", encoding="utf-8") as f:
51
  config = yaml.safe_load(f) or {}
52
 
53
- # 更新配置结构
54
  if "api_keys" not in config:
55
  config["api_keys"] = {}
 
56
  config["api_keys"]["gemini_api_key"] = api_key
57
 
58
- # 写入文件
59
- with open(CONFIG_PATH, "w", encoding="utf-8") as f:
60
  yaml.dump(config, f, allow_unicode=True, default_flow_style=False)
61
 
62
- # 立即读取验证并打印
63
- with open(CONFIG_PATH, "r", encoding="utf-8") as f:
64
- verify_content = f.read()
65
- logger("Config file updated. Current content (REDACTED):")
66
- # 出于安全考虑,日志里只打印 key 的前几位
67
- logger(verify_content.replace(api_key, api_key[:5] + "******"))
68
 
69
- return "Gemini API Key updated and verified in config.yaml!"
70
  except Exception as e:
71
- logger(f"Error saving config: {str(e)}")
72
- return f"Error: {str(e)}"
73
 
74
- # --- UI 界面 ---
75
- with gr.Blocks() as demo:
76
- gr.Markdown("# 📄 AI Paper Assistant")
77
 
78
- with gr.Tab("1. System Setup"):
79
- gr.Markdown("### 🔑 API Configuration\nConfigure your keys before processing PDFs.")
80
- api_input = gr.Textbox(label="Gemini API Key", type="password", placeholder="sk-...")
81
- api_btn = gr.Button("Update Config")
82
- api_status = gr.Textbox(label="Config Status")
83
- api_btn.click(save_api_key, inputs=api_input, outputs=api_status)
84
 
85
- with gr.Tab("2. Upload & Process"):
86
- gr.Markdown("### 📁 PDF Upload\nUpload papers to the server's local storage.")
87
- pdf_input = gr.File(label="Choose PDF", file_types=[".pdf"])
88
- pdf_btn = gr.Button("Save to Papers Folder")
89
- pdf_status = gr.Textbox(label="Upload Status")
90
- pdf_btn.click(save_pdf, inputs=pdf_input, outputs=pdf_status)
91
 
92
  if __name__ == "__main__":
93
- logger("Application starting...")
 
94
  demo.launch()
 
4
  import shutil
5
  import sys
6
 
7
+ # 强制在启动时打印 START,并直接输出到 stderr 确保可见
8
+ print("==== [SYSTEM] APP STARTING... ====", file=sys.stderr, flush=True)
 
 
9
 
10
+ # 确保 papers 文件夹存在
11
+ os.makedirs("papers", exist_ok=True)
12
 
13
+ def debug_log(message):
14
+ """自定义调试函数,确保内容立即出现日志中"""
15
+ print(f"[DEBUG] {message}", file=sys.stderr, flush=True)
16
 
17
  def save_pdf(file):
18
  if file is None:
19
+ return "Please upload a PDF file."
20
 
21
+ debug_log(f"Received file: {file.name}")
22
+
23
+ # 获取文件名并保存
24
+ file_name = os.path.basename(file.name)
25
+ file_path = os.path.join("papers", file_name)
26
+ shutil.copy(file.name, file_path)
27
+
28
+ # 打印文件夹下的所有文件
29
+ all_files = os.listdir("papers")
30
+ debug_log(f"File saved to {file_path}")
31
+ debug_log(f"Current files in 'papers/': {all_files}")
32
+
33
+ return f"File '{file_name}' saved. Total files in folder: {len(all_files)}"
 
 
 
 
 
34
 
35
  def save_api_key(api_key):
36
+ if not api_key:
37
+ return "API Key cannot be empty."
38
+
39
+ config_path = "config.yaml"
40
+ debug_log("Attempting to save API Key...")
41
 
42
  try:
 
43
  config = {}
44
+ if os.path.exists(config_path):
45
+ with open(config_path, "r", encoding="utf-8") as f:
46
  config = yaml.safe_load(f) or {}
47
 
 
48
  if "api_keys" not in config:
49
  config["api_keys"] = {}
50
+
51
  config["api_keys"]["gemini_api_key"] = api_key
52
 
53
+ with open(config_path, "w", encoding="utf-8") as f:
 
54
  yaml.dump(config, f, allow_unicode=True, default_flow_style=False)
55
 
56
+ # 验证并打印 config 内容 (脱敏处理)
57
+ with open(config_path, "r", encoding="utf-8") as f:
58
+ current_config = f.read()
59
+ # 打印前20个字符确认文件结构,不打印完整 key
60
+ debug_log(f"Config updated. Content preview: {current_config[:20]}...")
 
61
 
62
+ return "Gemini API Key updated successfully!"
63
  except Exception as e:
64
+ debug_log(f"ERROR: {str(e)}")
65
+ return f"Error: {str(e)}"
66
 
67
+ with gr.Blocks(title="PDF Uploader & Config") as demo:
68
+ gr.Markdown("# PDF and API Configuration")
 
69
 
70
+ with gr.Tab("Upload PDF"):
71
+ file_input = gr.File(label="Upload your PDF", file_types=[".pdf"])
72
+ upload_btn = gr.Button("Save PDF")
73
+ upload_output = gr.Textbox(label="Status")
74
+ upload_btn.click(save_pdf, inputs=file_input, outputs=upload_output)
 
75
 
76
+ with gr.Tab("Gemini Configuration"):
77
+ key_input = gr.Textbox(label="Enter Gemini API Key", type="password")
78
+ key_btn = gr.Button("Save API Key")
79
+ key_output = gr.Textbox(label="Status")
80
+ key_btn.click(save_api_key, inputs=key_input, outputs=key_output)
 
81
 
82
  if __name__ == "__main__":
83
+ debug_log("Gradio Interface launching...")
84
+ # HF Spaces 环境下 server_name 和 port 通常由平台处理,简单 launch 即可
85
  demo.launch()