File size: 2,343 Bytes
fd45282
75ecc06
 
fd45282
f5f891b
c0ba1b5
75ecc06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c753e
 
1c0fdf3
75ecc06
1c0fdf3
14c753e
1c0fdf3
14c753e
1c0fdf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ecc06
 
 
 
5141e4c
 
 
 
75ecc06
5141e4c
 
75ecc06
 
5141e4c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import torch
import json

model_id = "deepseek-ai/deepseek-coder-1.3b-base"
lora_id = "Seunggg/lora-plant"

# 加载 tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)

# 加载基础模型,启用自动设备分配并脱载
base = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    offload_folder="offload/",
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    trust_remote_code=True
)

# 加载 LoRA adapter,同样启用脱载
model = PeftModel.from_pretrained(
    base,
    lora_id,
    offload_folder="offload/",
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
)

model.eval()

# 生成 pipeline
from transformers import pipeline
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    device_map="auto",
    max_new_tokens=256
)

from ask_api import ask_with_sensor  # 引入调用函数

def respond(user_input):
    if not user_input.strip():
        return "请输入植物相关的问题 😊"

    # 获取 Render 实时传感器数据
    try:
        sensor_response = requests.get("https://arduino-realtime.onrender.com/api/data", timeout=5)
        sensor_data = sensor_response.json().get("sensorData", None)
    except Exception as e:
        sensor_data = None

    # 生成用于 LoRA 本地推理的 prompt
    prompt = f"用户提问:{user_input}\n"
    if sensor_data:
        prompt += f"当前传感器数据:{json.dumps(sensor_data, ensure_ascii=False)}\n"
    prompt += "请用更人性化的语言生成建议,并推荐相关植物文献或资料。\n回答:"

    # 本地 LoRA 推理
    try:
        result = pipe(prompt)
        return result[0]["generated_text"]
    except Exception as e:
        return f"生成建议时出错:{str(e)}"

# Gradio 界面
gr.Interface(
    fn=respond,
    inputs=[
        gr.Textbox(lines=4, label="植物问题"),
        gr.Textbox(lines=2, label="传感器数据 (JSON 格式)", placeholder='{"temperature": 25, "humidity": 60}')
    ],
    outputs="text",
    title="🌱 植物助手 - 本地 LoRA + Render 联动版",
    description="结合本地建议和传感器分析结果。"
).launch()