chenkw1029 commited on
Commit
43e2c94
·
verified ·
1 Parent(s): c421256

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -39
app.py CHANGED
@@ -7,8 +7,9 @@ from transformers import pipeline, set_seed
7
  # 设置随机种子
8
  set_seed(42)
9
 
10
- # 尝试从环境变量获取 token
11
- HF_TOKEN = os.environ.get('HF_TOKEN', '')
 
12
 
13
  # 初始化模型管道
14
  try:
@@ -19,16 +20,16 @@ try:
19
  torch_dtype="auto"
20
  )
21
  MODEL_LOADED = True
22
- print("模型加载成功")
23
  except Exception as e:
24
- print(f"模型加载失败: {e}")
25
  MODEL_LOADED = False
26
  protein_generator = None
27
 
28
  def generate_with_local_model(instruction, max_length=100):
29
  """使用本地加载的模型生成蛋白质序列"""
30
  if not MODEL_LOADED or protein_generator is None:
31
- return "模型未正确加载,请检查控制台日志"
32
 
33
  try:
34
  result = protein_generator(
@@ -41,17 +42,17 @@ def generate_with_local_model(instruction, max_length=100):
41
  )
42
 
43
  if result and len(result) > 0:
44
- return result[0]['generated_text']
45
  else:
46
- return "生成失败,未获得有效结果"
47
 
48
  except Exception as e:
49
- return f"生成过程中出现错误: {str(e)}"
50
 
51
  def generate_with_api(instruction, max_length=100):
52
  """使用HuggingFace API生成蛋白质序列"""
53
  if not HF_TOKEN:
54
- return "未设置 HuggingFace Token,无法使用 API 功能。请在环境变量中设置 HF_TOKEN。"
55
 
56
  try:
57
  API_URL = "https://api-inference.huggingface.co/models/mzcwd/ProtTeX"
@@ -71,27 +72,36 @@ def generate_with_api(instruction, max_length=100):
71
  }
72
  }
73
 
74
- response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
 
75
 
76
  if response.status_code == 200:
77
  result = response.json()
78
  if isinstance(result, list) and len(result) > 0:
79
- return result[0].get('generated_text', '生成成功但无内容返回')
80
- return str(result)
 
81
  else:
82
- return f"API请求失败 (状态码: {response.status_code})\n响应: {response.text}"
 
 
 
83
 
84
  except requests.exceptions.Timeout:
85
- return "请求超时,请稍后重试"
86
  except Exception as e:
87
- return f"API调用错误: {str(e)}"
88
 
89
  def generate_protein(instruction, max_length=100):
90
  """主生成函数"""
91
- yield "正在处理您的请求..."
92
  time.sleep(0.5)
93
 
94
  try:
 
 
 
 
95
  # 优先使用本地模型,失败时使用API
96
  if MODEL_LOADED:
97
  result = generate_with_local_model(instruction, max_length)
@@ -101,25 +111,24 @@ def generate_protein(instruction, max_length=100):
101
  yield result
102
 
103
  except Exception as e:
104
- yield f"生成过程中出现未预期错误: {str(e)}"
105
 
106
- # 创建界面
107
- with gr.Blocks(
108
- title="ProtTeX 蛋白质生成器",
109
- theme=gr.themes.Soft()
110
- ) as demo:
111
 
112
  gr.Markdown("""
113
  # 🧬 ProtTeX 蛋白质生成器
114
 
115
- 使用自然语言指令生成蛋白质序列。输入您想要的蛋白质特性描述,AI将生成相应的蛋白质序列。
 
 
116
  """)
117
 
118
  with gr.Row():
119
- with gr.Column():
120
  instruction = gr.Textbox(
121
- label="蛋白质生成指令",
122
- placeholder="例如:Generate a protein with alpha-helical structure",
123
  lines=3,
124
  value="Generate a hydrophobic transmembrane protein sequence"
125
  )
@@ -129,33 +138,54 @@ with gr.Blocks(
129
  maximum=300,
130
  value=150,
131
  step=10,
132
- label="序列最大长度"
133
  )
134
 
135
- generate_btn = gr.Button("🚀 生成蛋白质序列", variant="primary")
136
-
137
- with gr.Column():
 
 
 
138
  output = gr.Textbox(
139
- label="生成的蛋白质序列",
140
- lines=6,
141
- show_copy_button=True
142
  )
143
 
144
- gr.Markdown("### 示例指令")
145
- gr.Examples(
 
 
146
  examples=[
147
  ["Generate a hydrophobic transmembrane protein sequence"],
148
  ["Create a water-soluble protein with beta-sheet structure"],
149
- ["Design a protein with enzymatic activity for hydrolysis"]
 
150
  ],
151
- inputs=instruction
152
  )
153
 
 
154
  generate_btn.click(
155
  fn=generate_protein,
156
  inputs=[instruction, max_length],
157
- outputs=output
158
  )
 
 
 
 
 
 
 
 
 
 
 
159
 
160
  if __name__ == "__main__":
161
- demo.launch()
 
 
 
 
7
  # 设置随机种子
8
  set_seed(42)
9
 
10
+ # 从环境变量获取 token
11
+ HF_TOKEN = os.environ.get('HF_TOKEN')
12
+ print(f"Token 状态: {'已设置' if HF_TOKEN else '未设置'}")
13
 
14
  # 初始化模型管道
15
  try:
 
20
  torch_dtype="auto"
21
  )
22
  MODEL_LOADED = True
23
+ print("✅ 本地模型加载成功")
24
  except Exception as e:
25
+ print(f" 本地模型加载失败: {e}")
26
  MODEL_LOADED = False
27
  protein_generator = None
28
 
29
  def generate_with_local_model(instruction, max_length=100):
30
  """使用本地加载的模型生成蛋白质序列"""
31
  if not MODEL_LOADED or protein_generator is None:
32
+ return "模型未正确加载,请检查控制台日志"
33
 
34
  try:
35
  result = protein_generator(
 
42
  )
43
 
44
  if result and len(result) > 0:
45
+ return f"✅ 生成成功:\n\n{result[0]['generated_text']}"
46
  else:
47
+ return "生成失败,未获得有效结果"
48
 
49
  except Exception as e:
50
+ return f"生成过程中出现错误: {str(e)}"
51
 
52
  def generate_with_api(instruction, max_length=100):
53
  """使用HuggingFace API生成蛋白质序列"""
54
  if not HF_TOKEN:
55
+ return "未设置 HuggingFace Token,无法使用 API 功能"
56
 
57
  try:
58
  API_URL = "https://api-inference.huggingface.co/models/mzcwd/ProtTeX"
 
72
  }
73
  }
74
 
75
+ print("🔄 正在调用 API...")
76
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
77
 
78
  if response.status_code == 200:
79
  result = response.json()
80
  if isinstance(result, list) and len(result) > 0:
81
+ generated_text = result[0].get('generated_text', '生成成功但无内容返回')
82
+ return f"✅ API 生成成功:\n\n{generated_text}"
83
+ return f"✅ API 响应: {str(result)}"
84
  else:
85
+ error_msg = f"API请求失败 (状态码: {response.status_code})"
86
+ if response.text:
87
+ error_msg += f"\n详细信息: {response.text}"
88
+ return error_msg
89
 
90
  except requests.exceptions.Timeout:
91
+ return "请求超时,请稍后重试"
92
  except Exception as e:
93
+ return f"API调用错误: {str(e)}"
94
 
95
  def generate_protein(instruction, max_length=100):
96
  """主生成函数"""
97
+ yield "🔄 正在处理您的请求..."
98
  time.sleep(0.5)
99
 
100
  try:
101
+ # 显示当前模式
102
+ mode = "本地模型" if MODEL_LOADED else "API调用"
103
+ yield f"🔄 使用 {mode} 处理中..."
104
+
105
  # 优先使用本地模型,失败时使用API
106
  if MODEL_LOADED:
107
  result = generate_with_local_model(instruction, max_length)
 
111
  yield result
112
 
113
  except Exception as e:
114
+ yield f"生成过程中出现未预期错误: {str(e)}"
115
 
116
+ # 创建界面 - 移除了不兼容的参数
117
+ with gr.Blocks(title="ProtTeX 蛋白质生成器") as demo:
 
 
 
118
 
119
  gr.Markdown("""
120
  # 🧬 ProtTeX 蛋白质生成器
121
 
122
+ **使用自然语言指令生成蛋白质序列**
123
+
124
+ *当前模式: {'🧠 本地模型' if MODEL_LOADED else '🌐 API 调用'} | Token: {'✅ 已设置' if HF_TOKEN else '❌ 未设置'}*
125
  """)
126
 
127
  with gr.Row():
128
+ with gr.Column(scale=1):
129
  instruction = gr.Textbox(
130
+ label="🧪 蛋白质生成指令",
131
+ placeholder="例如:Generate a protein with alpha-helical structure for membrane binding",
132
  lines=3,
133
  value="Generate a hydrophobic transmembrane protein sequence"
134
  )
 
138
  maximum=300,
139
  value=150,
140
  step=10,
141
+ label="📏 序列最大长度"
142
  )
143
 
144
+ generate_btn = gr.Button(
145
+ "🚀 生成蛋白质序列",
146
+ variant="primary"
147
+ )
148
+
149
+ with gr.Column(scale=1):
150
  output = gr.Textbox(
151
+ label="🧬 生成的蛋白质序列",
152
+ lines=8
153
+ # 移除了 show_copy_button 参数
154
  )
155
 
156
+ # 示例部分
157
+ gr.Markdown("### 💡 示例指令(点击试用)")
158
+
159
+ examples = gr.Examples(
160
  examples=[
161
  ["Generate a hydrophobic transmembrane protein sequence"],
162
  ["Create a water-soluble protein with beta-sheet structure"],
163
+ ["Design a protein with enzymatic activity for hydrolysis"],
164
+ ["Generate a stable protein for high temperature environments"]
165
  ],
166
+ inputs=[instruction]
167
  )
168
 
169
+ # 连接按钮事件
170
  generate_btn.click(
171
  fn=generate_protein,
172
  inputs=[instruction, max_length],
173
+ outputs=[output]
174
  )
175
+
176
+ # 状态信息
177
+ gr.Markdown(f"""
178
+ ---
179
+ **系统状态**:
180
+ - 运行模式: {'🧠 本地模型' if MODEL_LOADED else '🌐 API 调用'}
181
+ - Token 状态: {'✅ 已设置' if HF_TOKEN else '❌ 未设置'}
182
+ - 硬件: CPU Basic
183
+
184
+ *基于 [mzcwd/ProtTeX](https://huggingface.co/mzcwd/ProtTeX) 模型*
185
+ """)
186
 
187
  if __name__ == "__main__":
188
+ demo.launch(
189
+ server_name="0.0.0.0",
190
+ share=False
191
+ )