Zenithwang commited on
Commit
65038dc
·
verified ·
1 Parent(s): 68e1623

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -11
app.py CHANGED
@@ -1,36 +1,55 @@
1
  import os
 
 
2
  import gradio as gr
 
3
  from openai import OpenAI
4
 
5
- # 读取 API 密钥和端点
 
 
 
 
 
 
6
  client = OpenAI(
7
- api_key=os.getenv("stepfun_key"),
8
- base_url="https://platform.stepfun.com/v1"
9
  )
10
 
11
- def chat_with_step3(image, question):
12
- """上传图片和文本,通过 API 请求 step3 推理。"""
 
 
 
 
 
 
13
  messages = [
14
  {
15
  "role": "user",
16
  "content": [
17
- {"type": "image_url", "image_url": {"url": image}},
18
  {"type": "text", "text": question},
19
  ],
20
  }
21
  ]
22
- completion = client.chat.completions.create(
23
- model="step3", messages=messages, max_tokens=4096
 
 
24
  )
25
- return completion.choices[0].message.content
26
 
27
  iface = gr.Interface(
28
  fn=chat_with_step3,
29
- inputs=[gr.Image(type="pil", label="Upload image"), gr.Textbox(label="Question")],
 
30
  outputs="text",
31
  title="Step3 FP8 (API) Demo",
32
- description="使用 StepFun 提供的 OpenAI 兼容 API 调用 step3fp8 模型。"
33
  )
34
 
35
  if __name__ == "__main__":
 
36
  iface.launch()
 
1
  import os
2
+ import io
3
+ import base64
4
  import gradio as gr
5
+ from PIL import Image
6
  from openai import OpenAI
7
 
8
+ def pil_to_data_url(img: Image.Image, fmt="PNG"):
9
+ buf = io.BytesIO()
10
+ img.save(buf, format=fmt)
11
+ b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
12
+ mime = "image/png" if fmt.upper() == "PNG" else "image/jpeg"
13
+ return f"data:{mime};base64,{b64}"
14
+
15
  client = OpenAI(
16
+ api_key=os.getenv("STEPFUN_KEY"), # 在 HF Secrets 里配置
17
+ base_url="https://platform.stepfun.com/v1",
18
  )
19
 
20
+ def chat_with_step3(image: Image.Image, question: str):
21
+ if image is None:
22
+ return "请先上传图片。"
23
+ if not question:
24
+ question = "请描述这张图片。"
25
+
26
+ data_url = pil_to_data_url(image, fmt="PNG")
27
+
28
  messages = [
29
  {
30
  "role": "user",
31
  "content": [
32
+ {"type": "image_url", "image_url": {"url": data_url}},
33
  {"type": "text", "text": question},
34
  ],
35
  }
36
  ]
37
+ resp = client.chat.completions.create(
38
+ model="step3-fp8", # 更稳妥的模型名
39
+ messages=messages,
40
+ max_tokens=1024,
41
  )
42
+ return resp.choices[0].message.content
43
 
44
  iface = gr.Interface(
45
  fn=chat_with_step3,
46
+ inputs=[gr.Image(type="pil", label="Upload image"),
47
+ gr.Textbox(label="Question")],
48
  outputs="text",
49
  title="Step3 FP8 (API) Demo",
50
+ description="使用 StepFun OpenAI 兼容 API 调用 step3-fp8 模型。"
51
  )
52
 
53
  if __name__ == "__main__":
54
+ # HF Spaces 内不必 share=True;保持默认即可
55
  iface.launch()