chenkw1029 commited on
Commit
7fe5ef7
·
verified ·
1 Parent(s): a06cf6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -75
app.py CHANGED
@@ -1,104 +1,131 @@
1
  import gradio as gr
2
- from transformers import pipeline
3
  import requests
4
-
5
- # 初始化模型(使用较简单的初始化方式避免内存问题)
6
- def load_model():
7
- try:
8
- # 尝试加载模型,如果内存不足则使用API
9
- protein_pipeline = pipeline(
10
- "text-generation",
11
- model="mzcwd/ProtTeX",
12
- device=0 if torch.cuda.is_available() else -1
13
- )
14
- return protein_pipeline
15
- except Exception as e:
16
- print(f"模型加载失败: {e}")
17
- return None
18
-
19
- model = load_model()
20
 
21
  def generate_protein(instruction, max_length=100):
22
  """生成蛋白质序列"""
23
 
24
- # 如果本地模型加载失败,使用HuggingFace API
25
- if model is None:
26
- try:
27
- API_URL = "https://api-inference.huggingface.co/models/mzcwd/ProtTeX"
28
- headers = {"Authorization": f"Bearer {os.environ.get('ProtTex', '')}"} # 需要替换成您的token
29
-
30
- response = requests.post(API_URL, json={
31
- "inputs": instruction,
32
- "parameters": {"max_length": max_length}
33
- })
34
-
35
- if response.status_code == 200:
36
- result = response.json()
37
- return result[0]['generated_text']
38
- else:
39
- return f"API调用失败: {response.status_code}"
40
-
41
- except Exception as e:
42
- return f"错误: {str(e)}"
43
 
44
- # 使用本地模型
45
  try:
46
- result = model(
47
- instruction,
48
- max_length=max_length,
49
- num_return_sequences=1,
50
- temperature=0.7
51
- )
52
- return result[0]['generated_text']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  except Exception as e:
54
- return f"生成失败: {str(e)}"
55
-
56
- # 示例指令
57
- examples = [
58
- "Generate a protein sequence with alpha-helical structure",
59
- "Create a beta-sheet rich protein for structural stability",
60
- "Design a hydrophilic protein for aqueous environments",
61
- "Generate a transmembrane protein sequence"
62
- ]
63
 
64
  # 创建界面
65
- with gr.Blocks(title="ProtTeX 蛋白质生成器") as demo:
66
- gr.Markdown("# 🧬 ProtTeX 蛋白质生成器")
67
- gr.Markdown("输入自然语言指令,生成蛋白质序列")
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  with gr.Row():
70
- with gr.Column():
71
  instruction = gr.Textbox(
72
- label="输入指令",
73
- placeholder="例如:Generate a protein sequence with alpha-helical structure",
74
- lines=3
 
75
  )
 
76
  max_length = gr.Slider(
77
- minimum=50,
78
- maximum=200,
79
- value=100,
80
- label="生成长度"
 
81
  )
82
- generate_btn = gr.Button("生成蛋白质���列", variant="primary")
83
-
84
- with gr.Column():
 
 
 
 
 
85
  output = gr.Textbox(
86
- label="生成的序列",
87
- lines=5,
 
88
  interactive=False
89
  )
90
 
91
- gr.Markdown("## 示例指令")
92
- gr.Examples(
93
- examples=examples,
94
- inputs=instruction
 
 
 
 
 
 
 
 
 
 
 
95
  )
96
 
 
97
  generate_btn.click(
98
  fn=generate_protein,
99
  inputs=[instruction, max_length],
100
- outputs=output
101
  )
 
 
 
 
 
 
102
 
103
  if __name__ == "__main__":
104
- demo.launch(debug=True, share=True)
 
 
 
 
1
  import gradio as gr
 
2
  import requests
3
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def generate_protein(instruction, max_length=100):
6
  """生成蛋白质序列"""
7
 
8
+ # 显示加载状态
9
+ yield "正在生成蛋白质序列,请稍候..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
 
11
  try:
12
+ API_URL = "https://api-inference.huggingface.co/models/mzcwd/ProtTeX"
13
+
14
+ payload = {
15
+ "inputs": instruction,
16
+ "parameters": {
17
+ "max_length": max_length,
18
+ "temperature": 0.8,
19
+ "do_sample": True,
20
+ "return_full_text": False
21
+ },
22
+ "options": {
23
+ "wait_for_model": True
24
+ }
25
+ }
26
+
27
+ # 发送请求到 HuggingFace 推理 API
28
+ response = requests.post(API_URL, json=payload)
29
+
30
+ if response.status_code == 200:
31
+ result = response.json()
32
+ if isinstance(result, list) and len(result) > 0:
33
+ generated_text = result[0].get('generated_text', '')
34
+ yield generated_text if generated_text else "模型已响应但未生成内容"
35
+ else:
36
+ yield f"响应格式异常: {result}"
37
+ elif response.status_code == 503:
38
+ # 模型正在加载,等待后重试
39
+ yield "模型正在启动中,请等待约30秒后重试..."
40
+ else:
41
+ error_msg = f"请求失败 (状态码: {response.status_code})"
42
+ if response.status_code == 401:
43
+ error_msg += "\n可能需要设置访问令牌"
44
+ yield error_msg
45
+
46
  except Exception as e:
47
+ yield f"发生错误: {str(e)}"
 
 
 
 
 
 
 
 
48
 
49
  # 创建界面
50
+ with gr.Blocks(
51
+ title="ProtTeX 蛋白质生成器",
52
+ theme=gr.themes.Soft(),
53
+ css="""
54
+ .gradio-container {
55
+ max-width: 800px !important;
56
+ }
57
+ """
58
+ ) as demo:
59
+
60
+ gr.Markdown("""
61
+ # 🧬 ProtTeX 蛋白质生成器
62
+
63
+ 使用自然语言指令生成蛋白质序列。输入您想要的蛋白质特性描述,AI将生成相应的蛋白质序列。
64
+ """)
65
 
66
  with gr.Row():
67
+ with gr.Column(scale=1):
68
  instruction = gr.Textbox(
69
+ label="蛋白质生成指令",
70
+ placeholder="例如:Generate a protein with alpha-helical structure for membrane binding",
71
+ lines=3,
72
+ max_lines=5
73
  )
74
+
75
  max_length = gr.Slider(
76
+ minimum=50,
77
+ maximum=300,
78
+ value=150,
79
+ step=10,
80
+ label="序列最大长度"
81
  )
82
+
83
+ generate_btn = gr.Button(
84
+ "🚀 生成蛋白质序列",
85
+ variant="primary",
86
+ size="lg"
87
+ )
88
+
89
+ with gr.Column(scale=1):
90
  output = gr.Textbox(
91
+ label="生成的蛋白质序列",
92
+ lines=6,
93
+ show_copy_button=True,
94
  interactive=False
95
  )
96
 
97
+ # 示例部分
98
+ gr.Markdown("### 💡 示例指令")
99
+
100
+ examples = gr.Examples(
101
+ examples=[
102
+ ["Generate a hydrophobic transmembrane protein sequence"],
103
+ ["Create a water-soluble protein with beta-sheet structure"],
104
+ ["Design a protein with enzymatic activity for hydrolysis"],
105
+ ["Generate a stable protein for high temperature environments"]
106
+ ],
107
+ inputs=[instruction],
108
+ outputs=[output],
109
+ fn=generate_protein,
110
+ cache_examples=False,
111
+ label="点击示例快速尝试"
112
  )
113
 
114
+ # 连接按钮事件
115
  generate_btn.click(
116
  fn=generate_protein,
117
  inputs=[instruction, max_length],
118
+ outputs=[output]
119
  )
120
+
121
+ # 页脚信息
122
+ gr.Markdown("""
123
+ ---
124
+ *基于 [mzcwd/ProtTeX](https://huggingface.co/mzcwd/ProtTeX) 模型*
125
+ """)
126
 
127
  if __name__ == "__main__":
128
+ demo.launch(
129
+ server_name="0.0.0.0",
130
+ share=False
131
+ )