Zenithwang commited on
Commit
e1d60fa
·
verified ·
1 Parent(s): 61b5a56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -49
app.py CHANGED
@@ -1,36 +1,50 @@
1
- import io
2
  import os
 
3
  import base64
4
  from typing import Optional
5
 
6
  import httpx
7
- from PIL import Image
8
  import gradio as gr
 
9
  from fastapi import FastAPI
10
 
11
- # ========== 配置 ==========
12
  STEPFUN_ENDPOINT = os.getenv("STEPFUN_ENDPOINT", "https://api.stepfun.com/v1")
13
- MODEL_NAME = os.getenv("STEPFUN_MODEL", "step-3")
14
- TITLE = "StepFun · 图像问答(step-3"
15
- DESC = "上传图片 + 输入问题,走 StepFun OpenAI 兼容接口 /chat/completions"
16
- # =========================
 
 
17
 
18
  def _get_api_key() -> Optional[str]:
19
- # 兼容两种环境变量名
 
 
 
20
  return os.getenv("OPENAI_API_KEY") or os.getenv("STEPFUN_KEY")
21
 
 
22
  def _pil_to_data_url(img: Image.Image, fmt: str = "PNG") -> str:
 
 
 
23
  buf = io.BytesIO()
24
  img.save(buf, format=fmt)
25
  b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
26
  mime = "image/png" if fmt.upper() == "PNG" else "image/jpeg"
27
  return f"data:{mime};base64,{b64}"
28
 
29
- def _post_chat(messages: list, temperature: float = 0.7, timeout: float = 60.0) -> str:
 
 
 
 
30
  key = _get_api_key()
31
  if not key:
32
  raise RuntimeError(
33
- "API Key 未设置。请在 Space 的 Settings → Variables and secrets 添加:\n"
 
34
  "OPENAI_API_KEY 或 STEPFUN_KEY(值为 StepFun API Key)。"
35
  )
36
 
@@ -44,16 +58,25 @@ def _post_chat(messages: list, temperature: float = 0.7, timeout: float = 60.0)
44
  "messages": messages,
45
  "temperature": temperature,
46
  }
47
- r = httpx.post(url, headers=headers, json=payload, timeout=timeout)
48
- r.raise_for_status()
49
- data = r.json()
50
- # 兼容常见返回结构
 
51
  return data["choices"][0]["message"]["content"]
52
 
53
- def infer(image: Optional[Image.Image], question: Optional[str]) -> str:
 
 
 
 
54
  if image is None:
55
- return "请先上传图片再提问。"
56
- q = (question or "").strip() or "请描述这张图片。"
 
 
 
 
57
  data_url = _pil_to_data_url(image, fmt="PNG")
58
  messages = [
59
  {
@@ -64,46 +87,49 @@ def infer(image: Optional[Image.Image], question: Optional[str]) -> str:
64
  ],
65
  }
66
  ]
 
67
  try:
68
  return _post_chat(messages)
69
  except httpx.HTTPStatusError as e:
70
- return f"调用失败(HTTP {e.response.status_code}):{e.response.text}"
 
 
 
 
 
71
  except Exception as e:
72
  return f"调用失败:{repr(e)}"
73
 
74
- # ------- Gradio 界面 -------
75
- demo = gr.Interface(
76
- fn=infer,
77
- inputs=[
78
- gr.Image(type="pil", label="上传图片"),
79
- gr.Textbox(label="问题", placeholder="例如:这是什么菜?怎么做?"),
80
- ],
81
- outputs=gr.Textbox(label="回答"),
82
- title=TITLE,
83
- description=DESC,
84
- )
85
-
86
- # ------- FastAPI 宿主应用(覆盖 /info,避免 gradio_client 的 schema 解析) -------
87
- fastapi_app = FastAPI()
88
-
89
- @fastapi_app.get("/health")
90
- def health():
91
- return {"status": "ok"}
92
-
93
- @fastapi_app.get("/info")
94
- def info_stub():
95
- # 返回一个最小可用的对象,绕过 gradio 的 api_info 复杂逻辑
96
- return {
97
- "api": False,
98
- "message": "API docs 已禁用(此路由由外部 FastAPI 覆盖以规避依赖冲突)。"
99
- }
100
 
101
- # 挂载 Gradio 到根路径
102
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- # 本地调试:python app.py
105
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
106
  import uvicorn
 
107
  port = int(os.getenv("PORT", "7860"))
108
- # 注意:本地调试可以启;Spaces 不会走这里
109
  uvicorn.run(app, host="0.0.0.0", port=port)
 
 
1
  import os
2
+ import io
3
  import base64
4
  from typing import Optional
5
 
6
  import httpx
 
7
  import gradio as gr
8
+ from PIL import Image
9
  from fastapi import FastAPI
10
 
11
+ # --------- 基本配置 ---------
12
  STEPFUN_ENDPOINT = os.getenv("STEPFUN_ENDPOINT", "https://api.stepfun.com/v1")
13
+ MODEL_NAME = os.getenv("MODEL_NAME", "step-3")
14
+ TITLE = "StepFun · step-3 图片问答 Demo"
15
+ DESC = "上传一张图片,问一个问题;后台通过 StepFun OpenAI 兼容接口完成图文对话。"
16
+ FOOTER = "提示:在 HF Spaces 的 Settings -> Variables 里设置 OPENAI_API_KEY 或 STEPFUN_KEY"
17
+ # ---------------------------
18
+
19
 
20
  def _get_api_key() -> Optional[str]:
21
+ """
22
+ 从环境变量里取 API Key。
23
+ 优先 OPENAI_API_KEY(OpenAI 兼容接口的常用名),否则退回 STEPFUN_KEY。
24
+ """
25
  return os.getenv("OPENAI_API_KEY") or os.getenv("STEPFUN_KEY")
26
 
27
+
28
  def _pil_to_data_url(img: Image.Image, fmt: str = "PNG") -> str:
29
+ """
30
+ PIL.Image -> data:image/...;base64,... (OpenAI兼容的 image_url 需要)
31
+ """
32
  buf = io.BytesIO()
33
  img.save(buf, format=fmt)
34
  b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
35
  mime = "image/png" if fmt.upper() == "PNG" else "image/jpeg"
36
  return f"data:{mime};base64,{b64}"
37
 
38
+
39
+ def _post_chat(messages: list, temperature: float = 0.7) -> str:
40
+ """
41
+ 直接用 httpx 调用 StepFun 的 /chat/completions 接口,返回文本。
42
+ """
43
  key = _get_api_key()
44
  if not key:
45
  raise RuntimeError(
46
+ "API Key 未设置。\n"
47
+ "请在本地环境变量或 HF Spaces -> Settings -> Variables 里设置:\n"
48
  "OPENAI_API_KEY 或 STEPFUN_KEY(值为 StepFun API Key)。"
49
  )
50
 
 
58
  "messages": messages,
59
  "temperature": temperature,
60
  }
61
+
62
+ # 简单超时与错误抛出
63
+ resp = httpx.post(url, headers=headers, json=payload, timeout=60)
64
+ resp.raise_for_status()
65
+ data = resp.json()
66
  return data["choices"][0]["message"]["content"]
67
 
68
+
69
+ def chat_with_step3(image: Optional[Image.Image], question: Optional[str]) -> str:
70
+ """
71
+ Gradio 回调函数:输入图片和问题,返回模型回答。
72
+ """
73
  if image is None:
74
+ return "请先上传图片。"
75
+
76
+ q = (question or "").strip()
77
+ if not q:
78
+ q = "请描述这张图片的内容,并指出可能的菜品名称与做法要点。"
79
+
80
  data_url = _pil_to_data_url(image, fmt="PNG")
81
  messages = [
82
  {
 
87
  ],
88
  }
89
  ]
90
+
91
  try:
92
  return _post_chat(messages)
93
  except httpx.HTTPStatusError as e:
94
+ # 返回后端具体错误信息,便于排障
95
+ try:
96
+ detail = e.response.json()
97
+ except Exception:
98
+ detail = e.response.text
99
+ return f"后端返回错误:HTTP {e.response.status_code}\n{detail}"
100
  except Exception as e:
101
  return f"调用失败:{repr(e)}"
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ # --------- 构建 Gradio 界面 ---------
105
+ with gr.Blocks(title=TITLE, analytics_enabled=False) as demo:
106
+ gr.Markdown(f"## {TITLE}")
107
+ gr.Markdown(DESC)
108
+
109
+ with gr.Row():
110
+ with gr.Column():
111
+ img_in = gr.Image(type="pil", label="上传图片")
112
+ txt_in = gr.Textbox(
113
+ label="问题(可留空)",
114
+ placeholder="例如:这是什么菜?做法是怎样的?",
115
+ )
116
+ btn = gr.Button("提交")
117
+ with gr.Column():
118
+ out = gr.Textbox(label="回答", lines=12)
119
+
120
+ btn.click(fn=chat_with_step3, inputs=[img_in, txt_in], outputs=out)
121
 
122
+ gr.Markdown(f"<small>{FOOTER}</small>")
123
+
124
+ # 让 HF Spaces 识别到 FastAPI/ASGI 应用
125
+ app = FastAPI()
126
+ # 不使用自定义路径参数,直接挂载到根路径
127
+ app = gr.mount_gradio_app(app, demo, path="/")
128
+
129
+
130
+ # --------- 本地调试专用(Spaces 环境不会执行)---------
131
+ if __name__ == "__main__" and os.environ.get("SPACE_BUILD") is None:
132
  import uvicorn
133
+
134
  port = int(os.getenv("PORT", "7860"))
 
135
  uvicorn.run(app, host="0.0.0.0", port=port)