OpenIPOS commited on
Commit
cfff901
·
verified ·
1 Parent(s): 393d365

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -55
app.py CHANGED
@@ -1,104 +1,90 @@
1
  import os
2
  import gradio as gr
3
  import spaces
4
- import fitz # PyMuPDF
5
- import docx # python-docx
6
  from huggingface_hub import InferenceClient
7
 
8
- # 1. 引擎配置 (MiniMax-M2.5 229B)
9
- model_id = "MiniMaxAI/MiniMax-M2.5"
10
- client = InferenceClient(model_id, token=os.getenv("HF_TOKEN"))
 
 
 
 
 
 
11
 
12
- # 2. 全能文件解析解析器
13
  def extract_text(file_path):
14
  if not file_path: return ""
15
  try:
16
  ext = str(file_path).lower()
17
- # PDF 解析
18
  if ext.endswith(".pdf"):
19
  doc = fitz.open(file_path)
20
- text = "".join([page.get_text() for page in doc])
21
- doc.close()
22
- return text[:15000] # 适当截取,保证稳定性
23
- # Word 解析
24
  elif ext.endswith(".docx"):
25
  doc = docx.Document(file_path)
26
  return "\n".join([p.text for p in doc.paragraphs])[:15000]
27
- # 纯文本解析
28
  elif ext.endswith(".txt"):
29
  with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
30
  return f.read()[:15000]
31
- return f"[暂不支持直接解析此格式: {os.path.basename(file_path)}]"
32
- except Exception as e:
33
- return f"[解析失败: {str(e)}]"
34
 
35
  @spaces.GPU(duration=60)
36
  def chat_fn(message, history):
37
- # 强制历史记录清洗 (MiniMax API 对此非常敏感)
38
  clean_messages = []
39
  for turn in history:
40
- # 确保 content 永远是字符串
41
- u_content = turn.get("content", "")
42
- if not isinstance(u_content, str): u_content = str(u_content)
43
- clean_messages.append({"role": turn.get("role", "user"), "content": u_content})
44
 
45
- # 提取当前输入
46
  prompt_text = message.get("text", "")
47
  files = message.get("files", [])
48
 
49
- # 处理文件逻辑
50
- if files and len(files) > 0:
51
  f = files[0]
52
  file_path = f.get("path") if isinstance(f, dict) else f
53
  context = extract_text(file_path)
54
  if context:
55
- prompt_text = f"【参考文档】:\n{context}\n\n【指令】: {prompt_text}"
56
 
57
  clean_messages.append({"role": "user", "content": prompt_text})
58
 
59
  response = ""
60
  try:
61
- # 增加超时和异常保护
62
- stream = client.chat_completion(
63
  clean_messages,
64
  max_tokens=2048,
65
  stream=True,
66
- temperature=0.7
67
- )
68
-
69
- for msg in stream:
70
- # 严格检查 API 返回结构
71
- if hasattr(msg, 'choices') and len(msg.choices) > 0:
72
- delta = msg.choices[0].delta
73
- if hasattr(delta, 'content') and delta.content:
74
- response += delta.content
75
- yield response
76
 
77
  if response:
78
- response += "\n\n---\n> **OpenIPOS MegaNode | MiniMax-M2.5 极速逻辑引擎**"
79
- yield response
80
 
81
  except Exception as e:
82
- yield f"⚠️ 调度波动: {str(e)}。提示:由于模型发布初期访问量大,API 偶尔会返回 Error,请稍后重试。"
 
 
 
 
 
83
 
84
- # 3. 统一品牌装修
85
  with gr.Blocks(fill_height=True) as demo:
86
- with gr.Row():
87
- gr.HTML("""
88
- <div style="display: flex; align-items: center; gap: 20px; padding: 10px;">
89
- <img src="https://s3.bmp.ovh/2026/03/30/rIAGKg0O.png" style="height: 60px; width: auto;">
90
- <div>
91
- <h1 style="margin: 0; font-size: 24px;">OpenIPOS MegaNode</h1>
92
- <p style="margin: 0; color: #666;">中文精品人工智能算力出口 (MiniMax-M2.5)</p>
93
- </div>
94
- </div>
95
- """)
96
-
97
- gr.Markdown("---")
98
- # 开启多模态支持
99
  gr.ChatInterface(chat_fn, multimodal=True)
100
-
101
- gr.Markdown("---")
102
  gr.Markdown("© 2026 OpenIPOS Global Limited. 算力驱动:Hugging Face Inference Providers")
103
 
104
  demo.launch(theme=gr.themes.Soft())
 
1
  import os
2
  import gradio as gr
3
  import spaces
4
+ import fitz
5
+ import docx
6
  from huggingface_hub import InferenceClient
7
 
8
+ # 1. 强制显式调用 Token
9
+ hf_token = os.getenv("HF_TOKEN")
10
+ model_id = "MiniMaxAI/MiniMax-M2.5"
11
+
12
+ # 如果没有 Token,界面会直接提示
13
+ if not hf_token:
14
+ print("❌ 警告:未检测到 HF_TOKEN,请在 Settings -> Secrets 中添加")
15
+
16
+ client = InferenceClient(model_id, token=hf_token)
17
 
 
18
  def extract_text(file_path):
19
  if not file_path: return ""
20
  try:
21
  ext = str(file_path).lower()
 
22
  if ext.endswith(".pdf"):
23
  doc = fitz.open(file_path)
24
+ return "".join([page.get_text() for page in doc])[:15000]
 
 
 
25
  elif ext.endswith(".docx"):
26
  doc = docx.Document(file_path)
27
  return "\n".join([p.text for p in doc.paragraphs])[:15000]
 
28
  elif ext.endswith(".txt"):
29
  with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
30
  return f.read()[:15000]
31
+ return ""
32
+ except:
33
+ return ""
34
 
35
  @spaces.GPU(duration=60)
36
  def chat_fn(message, history):
37
+ # 彻底压扁历史记录为标准 API 格式
38
  clean_messages = []
39
  for turn in history:
40
+ clean_messages.append({"role": turn["role"], "content": str(turn["content"])})
 
 
 
41
 
 
42
  prompt_text = message.get("text", "")
43
  files = message.get("files", [])
44
 
45
+ if files:
 
46
  f = files[0]
47
  file_path = f.get("path") if isinstance(f, dict) else f
48
  context = extract_text(file_path)
49
  if context:
50
+ prompt_text = f"【参考文档】:\n{context}\n\n【指令说明】: 请基于以上内容回答:{prompt_text}"
51
 
52
  clean_messages.append({"role": "user", "content": prompt_text})
53
 
54
  response = ""
55
  try:
56
+ # 增加 headers 确保 Token 穿透
57
+ for msg in client.chat_completion(
58
  clean_messages,
59
  max_tokens=2048,
60
  stream=True,
61
+ temperature=0.7,
62
+ headers={"Authorization": f"Bearer {hf_token}"} if hf_token else None
63
+ ):
64
+ if msg.choices[0].delta.content:
65
+ response += msg.choices[0].delta.content
66
+ yield response
 
 
 
 
67
 
68
  if response:
69
+ yield response + "\n\n---\n> **OpenIPOS MegaNode | MiniMax-M2.5 极速逻辑节点**"
 
70
 
71
  except Exception as e:
72
+ # 如果是权限问题,这里会给出明确提示
73
+ err_msg = str(e)
74
+ if "401" in err_msg or "token" in err_msg.lower():
75
+ yield "❌ 授权失败:请检查 Space Settings 中的 HF_TOKEN 是否正确配置。"
76
+ else:
77
+ yield f"⚠️ 调度波动: {err_msg}。请尝试刷新重试。"
78
 
 
79
  with gr.Blocks(fill_height=True) as demo:
80
+ gr.HTML("""
81
+ <div style="display: flex; align-items: center; gap: 20px; padding: 10px;">
82
+ <img src="https://s3.bmp.ovh/2026/03/30/rIAGKg0O.png" style="height: 60px;">
83
+ <div><h1 style="margin: 0; font-size: 24px;">OpenIPOS MegaNode</h1>
84
+ <p style="margin: 0; color: #666;">中文精品人工智能算力出口 (MiniMax-M2.5)</p></div>
85
+ </div>
86
+ """)
 
 
 
 
 
 
87
  gr.ChatInterface(chat_fn, multimodal=True)
 
 
88
  gr.Markdown("© 2026 OpenIPOS Global Limited. 算力驱动:Hugging Face Inference Providers")
89
 
90
  demo.launch(theme=gr.themes.Soft())