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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -51
app.py CHANGED
@@ -2,78 +2,93 @@ import gradio as gr
2
  import os
3
  import yaml
4
  import shutil
 
5
 
6
- # 确保 papers 文件夹存在
7
- os.makedirs("papers", exist_ok=True)
 
 
 
 
 
 
 
 
 
8
 
9
  def save_pdf(file):
10
  if file is None:
11
- return "Please upload a PDF file."
12
 
13
- # 获取文件名并保存到 papers 文件夹
14
- file_name = os.path.basename(file.name)
15
- file_path = os.path.join("papers", file_name)
16
- shutil.copy(file.name, file_path)
17
-
18
- # --- 调试打印逻辑 ---
19
- print(f"\n[DEBUG] 正在检查 papers 文件夹内容...")
20
- files_in_dir = os.listdir("papers")
21
- print(f"[DEBUG] 当前 papers 目录下的文件列表: {files_in_dir}")
22
- # ------------------
23
-
24
- return f"File '{file_name}' saved successfully. Total files: {len(files_in_dir)}"
 
 
 
 
 
 
25
 
26
  def save_api_key(api_key):
27
- if not api_key:
28
- return "API Key cannot be empty."
29
 
30
- config_path = "config.yaml"
31
  try:
32
- # 如果文件不存在,初始化一个空字典
33
- if not os.path.exists(config_path):
34
- config = {}
35
- else:
36
- # 读取现有的 yaml 文件
37
- with open(config_path, "r", encoding="utf-8") as f:
38
  config = yaml.safe_load(f) or {}
39
 
40
- # 确保 api_keys 字典存在
41
  if "api_keys" not in config:
42
  config["api_keys"] = {}
43
-
44
- # 更新嵌套的键
45
  config["api_keys"]["gemini_api_key"] = api_key
46
 
47
- # 将更新后的内容文件
48
- with open(config_path, "w", encoding="utf-8") as f:
49
  yaml.dump(config, f, allow_unicode=True, default_flow_style=False)
 
 
 
 
 
 
 
50
 
51
- # --- 调试打印逻辑 ---
52
- print(f"\n[DEBUG] 正在验证 {config_path} 内容...")
53
- with open(config_path, "r", encoding="utf-8") as f:
54
- content = f.read()
55
- print(f"[DEBUG] 当前 config.yaml 内容:\n{content}")
56
- # ------------------
57
-
58
- return "Gemini API Key updated successfully in config.yaml!"
59
  except Exception as e:
60
- return f"Error saving API Key: {str(e)}"
 
61
 
62
- with gr.Blocks(title="PDF Uploader & Config") as demo:
63
- gr.Markdown("# PDF and API Configuration")
 
64
 
65
- with gr.Tab("Upload PDF"):
66
- file_input = gr.File(label="Upload your PDF", file_types=[".pdf"])
67
- upload_btn = gr.Button("Save PDF")
68
- upload_output = gr.Textbox(label="Status")
69
- upload_btn.click(save_pdf, inputs=file_input, outputs=upload_output)
 
70
 
71
- with gr.Tab("Gemini Configuration"):
72
- key_input = gr.Textbox(label="Enter Gemini API Key", type="password", placeholder="Paste your API key here...")
73
- key_btn = gr.Button("Save API Key")
74
- key_output = gr.Textbox(label="Status")
75
- key_btn.click(save_api_key, inputs=key_input, outputs=key_output)
 
76
 
77
  if __name__ == "__main__":
78
- # 在 HF Spaces 运行通常只需要 launch(),不需要手动指定端口
79
  demo.launch()
 
2
  import os
3
  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()