Seunggg commited on
Commit
c0ba1b5
·
verified ·
1 Parent(s): 456d778

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -12
app.py CHANGED
@@ -1,15 +1,46 @@
1
- import os, gradio as gr, openai
2
- openai.api_key = os.getenv("DEEPSEEK_API_KEY")
3
- def analyze_env(temperature, light, soil_humidity):
4
- msg = [
 
 
 
 
 
 
 
 
 
 
 
5
  {"role": "system", "content": "You are a plant care assistant."},
6
- {"role": "user", "content": f"Temperature: {temperature}°C, Light: {light} lux, Soil Humidity: {soil_humidity}%."}
 
7
  ]
8
- resp = openai.ChatCompletion.create(model="deepseek-chat", messages=msg, temperature=0.7)
9
- return resp.choices[0].message.content
10
- demo = gr.Interface(fn=analyze_env,
11
- inputs=[gr.Number(label="Temperature (°C)"), gr.Number(label="Light (lux)"), gr.Number(label="Soil Humidity (%)")],
12
- outputs="text",
13
- title="植物环境分析"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  )
15
- demo.launch()
 
 
 
1
+ import os, gradio as gr
2
+ from openai import OpenAI
3
+
4
+ # 初始化 DeepSeek 客户端
5
+ client = OpenAI(
6
+ api_key=os.getenv("DEEPSEEK_API_KEY"),
7
+ base_url="https://api.deepseek.com/v1"
8
+ )
9
+
10
+ def analyze_stream(temperature, light, soil_humidity):
11
+ """
12
+ 接收三个环境数据指标,调用 DeepSeek chat 模型进行流式分析。
13
+ 将生成的 token 实时 yield 回前端。
14
+ """
15
+ messages = [
16
  {"role": "system", "content": "You are a plant care assistant."},
17
+ {"role": "user", "content":
18
+ f"Temperature: {temperature}°C, Light: {light} lux, Soil Humidity: {soil_humidity}%."}
19
  ]
20
+ stream = client.chat.completions.create(
21
+ model="deepseek-chat",
22
+ messages=messages,
23
+ temperature=0.7,
24
+ stream=True
25
+ )
26
+ partial = ""
27
+ for chunk in stream:
28
+ delta = chunk.choices[0].delta.content or ""
29
+ partial += delta
30
+ yield partial # 持续输出拼接中的内容
31
+
32
+ # 定义 Gradio 界面
33
+ demo = gr.Interface(
34
+ fn=analyze_stream,
35
+ inputs=[
36
+ gr.Number(label="Temperature (°C)"),
37
+ gr.Number(label="Light (lux)"),
38
+ gr.Number(label="Soil Humidity (%)")
39
+ ],
40
+ outputs=gr.Textbox(label="DeepSeek 分析结果"),
41
+ title="🌱 实时植物环境分析",
42
+ description="输入当前环境参数后,系统将流式返回 DeepSeek 的分析建议。",
43
  )
44
+
45
+ # 启用 Gradio 的队列和流式输出
46
+ demo.queue(concurrency_count=2).launch(server_name="0.0.0.0")