C2MV commited on
Commit
15a2bb8
1 Parent(s): 8a4a425

Update interface.py

Browse files
Files changed (1) hide show
  1. interface.py +23 -399
interface.py CHANGED
@@ -12,30 +12,37 @@ from transformers import AutoTokenizer, AutoModelForCausalLM
12
  from sympy import symbols, sympify, lambdify
13
  import copy
14
  from config import DEVICE, MODEL_PATH, MAX_LENGTH, TEMPERATURE
15
- from decorators import spaces # Import the spaces class
16
 
 
17
  device = DEVICE
18
- model_path = MODEL_PATH
 
 
19
  tokenizer = AutoTokenizer.from_pretrained(model_path)
20
- model = AutoModelForCausalLM.from_pretrained(model_path).to(device).eval()
 
 
21
 
22
- @spaces.GPU(duration=100) # Apply the GPU decorator
23
  def generate_analysis(prompt, max_length=MAX_LENGTH):
24
  try:
25
  input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
 
 
26
  generated_ids = model.generate(
27
  input_ids=input_ids,
28
- max_length=max_length + len(input_ids[0]),
29
  temperature=TEMPERATURE,
30
  num_return_sequences=1,
31
  no_repeat_ngram_size=2,
32
  early_stopping=True
33
  )
 
34
  output_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
35
  analysis = output_text[len(prompt):].strip()
36
  return analysis
37
  except Exception as e:
38
- return f"An error occurred during analysis: {e}"
39
 
40
  def parse_bounds(bounds_str, num_params):
41
  try:
@@ -50,404 +57,21 @@ def parse_bounds(bounds_str, num_params):
50
  upper_bounds = [np.inf] * num_params
51
  return lower_bounds, upper_bounds
52
 
53
- @spaces.GPU(duration=100)
 
54
  def process_and_plot(
55
  file,
56
- biomass_eq1, biomass_eq2, biomass_eq3,
57
- biomass_param1, biomass_param2, biomass_param3,
58
- biomass_bound1, biomass_bound2, biomass_bound3,
59
- substrate_eq1, substrate_eq2, substrate_eq3,
60
- substrate_param1, substrate_param2, substrate_param3,
61
- substrate_bound1, substrate_bound2, substrate_bound3,
62
- product_eq1, product_eq2, product_eq3,
63
- product_param1, product_param2, product_param3,
64
- product_bound1, product_bound2, product_bound3,
65
- legend_position,
66
- show_legend,
67
- show_params,
68
- biomass_eq_count,
69
- substrate_eq_count,
70
- product_eq_count
71
  ):
72
- biomass_eqs = [biomass_eq1, biomass_eq2, biomass_eq3][:biomass_eq_count]
73
- biomass_params = [biomass_param1, biomass_param2, biomass_param3][:biomass_eq_count]
74
- biomass_bounds = [biomass_bound1, biomass_bound2, biomass_bound3][:biomass_eq_count]
75
-
76
- substrate_eqs = [substrate_eq1, substrate_eq2, substrate_eq3][:substrate_eq_count]
77
- substrate_params = [substrate_param1, substrate_param2, substrate_param3][:substrate_eq_count]
78
- substrate_bounds = [substrate_bound1, substrate_bound2, substrate_bound3][:substrate_eq_count]
79
-
80
- product_eqs = [product_eq1, product_eq2, product_eq3][:product_eq_count]
81
- product_params = [product_param1, product_param2, product_param3][:product_eq_count]
82
- product_bounds = [product_bound1, product_bound2, product_bound3][:product_eq_count]
83
-
84
- df = pd.read_excel(file.name)
85
- time = df['Time'].values
86
- biomass_data = df['Biomass'].values
87
- substrate_data = df['Substrate'].values
88
- product_data = df['Product'].values
89
-
90
- biomass_results = []
91
- substrate_results = []
92
- product_results = []
93
-
94
- for i in range(len(biomass_eqs)):
95
- equation = biomass_eqs[i]
96
- params_str = biomass_params[i]
97
- bounds_str = biomass_bounds[i]
98
-
99
- model = BioprocessModel()
100
- model.set_model('biomass', equation, params_str)
101
-
102
- params = [param.strip() for param in params_str.split(',')]
103
- lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
104
-
105
- y_pred = model.fit_model(
106
- 'biomass', time, biomass_data,
107
- bounds=(lower_bounds, upper_bounds)
108
- )
109
- biomass_results.append({
110
- 'model': copy.deepcopy(model),
111
- 'y_pred': y_pred,
112
- 'equation': equation
113
- })
114
-
115
- biomass_model = biomass_results[0]['model']
116
- X_t = biomass_model.models['biomass']['function']
117
- biomass_params_values = list(biomass_model.params['biomass'].values())
118
-
119
- for i in range(len(substrate_eqs)):
120
- equation = substrate_eqs[i]
121
- params_str = substrate_params[i]
122
- bounds_str = substrate_bounds[i]
123
-
124
- model = BioprocessModel()
125
-
126
- t_symbol = symbols('t')
127
- expr_substrate = sympify(equation)
128
- substrate_params_symbols = symbols([param.strip() for param in params_str.split(',')])
129
- substrate_func = lambdify(
130
- (t_symbol, *substrate_params_symbols),
131
- expr_substrate.subs('X(t)', X_t(t_symbol, *biomass_params_values)),
132
- 'numpy'
133
- )
134
- model.models['substrate'] = {
135
- 'function': substrate_func,
136
- 'params': [param.strip() for param in params_str.split(',')]
137
- }
138
-
139
- params = model.models['substrate']['params']
140
- lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
141
-
142
- y_pred = model.fit_model(
143
- 'substrate', time, substrate_data,
144
- bounds=(lower_bounds, upper_bounds)
145
- )
146
- substrate_results.append({
147
- 'model': copy.deepcopy(model),
148
- 'y_pred': y_pred,
149
- 'equation': equation
150
- })
151
-
152
- for i in range(len(product_eqs)):
153
- equation = product_eqs[i]
154
- params_str = product_params[i]
155
- bounds_str = product_bounds[i]
156
-
157
- model = BioprocessModel()
158
-
159
- t_symbol = symbols('t')
160
- expr_product = sympify(equation)
161
- product_params_symbols = symbols([param.strip() for param in params_str.split(',')])
162
- product_func = lambdify(
163
- (t_symbol, *product_params_symbols),
164
- expr_product.subs('X(t)', X_t(t_symbol, *biomass_params_values)),
165
- 'numpy'
166
- )
167
- model.models['product'] = {
168
- 'function': product_func,
169
- 'params': [param.strip() for param in params_str.split(',')]
170
- }
171
-
172
- params = model.models['product']['params']
173
- lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
174
-
175
- y_pred = model.fit_model(
176
- 'product', time, product_data,
177
- bounds=(lower_bounds, upper_bounds)
178
- )
179
- product_results.append({
180
- 'model': copy.deepcopy(model),
181
- 'y_pred': y_pred,
182
- 'equation': equation
183
- })
184
-
185
- fig, axs = plt.subplots(3, 1, figsize=(10, 15))
186
-
187
- # Biomass Plot
188
- axs[0].plot(time, biomass_data, 'o', label='Biomass Data')
189
- for i, result in enumerate(biomass_results):
190
- axs[0].plot(time, result['y_pred'], '-', label=f'Biomass Model {i+1}')
191
- axs[0].set_xlabel('Time')
192
- axs[0].set_ylabel('Biomass')
193
- if show_legend:
194
- axs[0].legend(loc=legend_position)
195
-
196
- # Substrate Plot
197
- axs[1].plot(time, substrate_data, 'o', label='Substrate Data')
198
- for i, result in enumerate(substrate_results):
199
- axs[1].plot(time, result['y_pred'], '-', label=f'Substrate Model {i+1}')
200
- axs[1].set_xlabel('Time')
201
- axs[1].set_ylabel('Substrate')
202
- if show_legend:
203
- axs[1].legend(loc=legend_position)
204
-
205
- # Product Plot
206
- axs[2].plot(time, product_data, 'o', label='Product Data')
207
- for i, result in enumerate(product_results):
208
- axs[2].plot(time, result['y_pred'], '-', label=f'Product Model {i+1}')
209
- axs[2].set_xlabel('Time')
210
- axs[2].set_ylabel('Product')
211
- if show_legend:
212
- axs[2].legend(loc=legend_position)
213
-
214
- plt.tight_layout()
215
- buf = io.BytesIO()
216
- plt.savefig(buf, format='png')
217
- buf.seek(0)
218
- image = Image.open(buf)
219
-
220
- all_results = {
221
- 'biomass_models': [],
222
- 'substrate_models': [],
223
- 'product_models': []
224
- }
225
-
226
- for i, result in enumerate(biomass_results):
227
- model_info = {
228
- 'model_number': i + 1,
229
- 'equation': result['equation'],
230
- 'parameters': result['model'].params['biomass'],
231
- 'R2': result['model'].r2['biomass'],
232
- 'RMSE': result['model'].rmse['biomass']
233
- }
234
- all_results['biomass_models'].append(model_info)
235
-
236
- for i, result in enumerate(substrate_results):
237
- model_info = {
238
- 'model_number': i + 1,
239
- 'equation': result['equation'],
240
- 'parameters': result['model'].params['substrate'],
241
- 'R2': result['model'].r2['substrate'],
242
- 'RMSE': result['model'].rmse['substrate']
243
- }
244
- all_results['substrate_models'].append(model_info)
245
-
246
- for i, result in enumerate(product_results):
247
- model_info = {
248
- 'model_number': i + 1,
249
- 'equation': result['equation'],
250
- 'parameters': result['model'].params['product'],
251
- 'R2': result['model'].r2['product'],
252
- 'RMSE': result['model'].rmse['product']
253
- }
254
- all_results['product_models'].append(model_info)
255
-
256
- results_text = "Experimental Results:\n\n"
257
-
258
- results_text += "Biomass Models:\n"
259
- for model_info in all_results['biomass_models']:
260
- results_text += f"""
261
- Model {model_info['model_number']}:
262
- Equation: {model_info['equation']}
263
- Parameters: {model_info['parameters']}
264
- R²: {model_info['R2']:.4f}
265
- RMSE: {model_info['RMSE']:.4f}
266
- """
267
-
268
- results_text += "\nSubstrate Models:\n"
269
- for model_info in all_results['substrate_models']:
270
- results_text += f"""
271
- Model {model_info['model_number']}:
272
- Equation: {model_info['equation']}
273
- Parameters: {model_info['parameters']}
274
- R²: {model_info['R2']:.4f}
275
- RMSE: {model_info['RMSE']:.4f}
276
- """
277
-
278
- results_text += "\nProduct Models:\n"
279
- for model_info in all_results['product_models']:
280
- results_text += f"""
281
- Model {model_info['model_number']}:
282
- Equation: {model_info['equation']}
283
- Parameters: {model_info['parameters']}
284
- R²: {model_info['R2']:.4f}
285
- RMSE: {model_info['RMSE']:.4f}
286
- """
287
-
288
- prompt = f"""
289
- You are an expert in bioprocess modeling.
290
-
291
- Analyze the following experimental results and provide a verdict on the quality of the models, suggesting improvements if necessary.
292
-
293
- {results_text}
294
-
295
- Your analysis should be detailed and professional.
296
- """
297
- analysis = generate_analysis(prompt)
298
-
299
- return [image], analysis
300
-
301
- def create_interface():
302
- with gr.Blocks() as demo:
303
- gr.Markdown("# Bioprocess Modeling Application with Yi-Coder Integration")
304
-
305
- file_input = gr.File(label="Upload Excel File")
306
-
307
- MAX_EQUATIONS = 3
308
- biomass_equations = []
309
- biomass_params = []
310
- biomass_bounds = []
311
- substrate_equations = []
312
- substrate_params = []
313
- substrate_bounds = []
314
- product_equations = []
315
- product_params = []
316
- product_bounds = []
317
-
318
- def create_model_inputs(model_name, equations_list, params_list, bounds_list):
319
- with gr.Column():
320
- gr.Markdown(f"### {model_name} Models")
321
- for i in range(MAX_EQUATIONS):
322
- with gr.Row(visible=(i == 0)) as row:
323
- equation_input = gr.Textbox(
324
- label=f"{model_name} Model {i+1} Equation",
325
- placeholder="Enter equation in terms of t and parameters",
326
- lines=1,
327
- value="" if i > 0 else "Default equation"
328
- )
329
- params_input = gr.Textbox(
330
- label=f"{model_name} Model {i+1} Parameters",
331
- placeholder="Comma-separated parameters",
332
- lines=1,
333
- value="" if i > 0 else "Parameters"
334
- )
335
- bounds_input = gr.Textbox(
336
- label=f"{model_name} Model {i+1} Bounds",
337
- placeholder="(lower, upper) for each parameter",
338
- lines=1
339
- )
340
- equations_list.append((row, equation_input))
341
- params_list.append(params_input)
342
- bounds_list.append(bounds_input)
343
- add_btn = gr.Button(f"Add {model_name} Equation")
344
- remove_btn = gr.Button(f"Remove {model_name} Equation")
345
- return add_btn, remove_btn
346
-
347
- with gr.Accordion("Model Definitions", open=True):
348
- with gr.Row():
349
- with gr.Column():
350
- add_biomass_btn, remove_biomass_btn = create_model_inputs(
351
- "Biomass", biomass_equations, biomass_params, biomass_bounds
352
- )
353
- with gr.Column():
354
- add_substrate_btn, remove_substrate_btn = create_model_inputs(
355
- "Substrate", substrate_equations, substrate_params, substrate_bounds
356
- )
357
- with gr.Column():
358
- add_product_btn, remove_product_btn = create_model_inputs(
359
- "Product", product_equations, product_params, product_bounds
360
- )
361
-
362
- legend_position = gr.Radio(
363
- choices=["upper left", "upper right", "lower left", "lower right", "best"],
364
- label="Legend Position",
365
- value="best"
366
- )
367
- show_legend = gr.Checkbox(label="Show Legend", value=True)
368
- show_params = gr.Checkbox(label="Show Parameters", value=True)
369
- simulate_btn = gr.Button("Simulate")
370
-
371
- with gr.Row():
372
- output_gallery = gr.Gallery(label="Results", columns=2, height='auto')
373
- analysis_output = gr.Textbox(label="Yi-Coder Analysis", lines=15)
374
-
375
- biomass_eq_count = gr.Number(value=1, visible=False)
376
- substrate_eq_count = gr.Number(value=1, visible=False)
377
- product_eq_count = gr.Number(value=1, visible=False)
378
-
379
- def add_equation(equations_list, eq_count):
380
- eq_count = min(eq_count + 1, MAX_EQUATIONS)
381
- for i, (row, _) in enumerate(equations_list):
382
- row.visible = i < eq_count
383
- return [row.update(visible=row.visible) for row, _ in equations_list], eq_count
384
-
385
- def remove_equation(equations_list, eq_count):
386
- eq_count = max(eq_count - 1, 1)
387
- for i, (row, _) in enumerate(equations_list):
388
- row.visible = i < eq_count
389
- return [row.update(visible=row.visible) for row, _ in equations_list], eq_count
390
-
391
- add_biomass_btn.click(
392
- fn=lambda eq_count: add_equation(biomass_equations, eq_count),
393
- inputs=biomass_eq_count,
394
- outputs=[*[row for row, _ in biomass_equations], biomass_eq_count]
395
- )
396
- remove_biomass_btn.click(
397
- fn=lambda eq_count: remove_equation(biomass_equations, eq_count),
398
- inputs=biomass_eq_count,
399
- outputs=[*[row for row, _ in biomass_equations], biomass_eq_count]
400
- )
401
-
402
- add_substrate_btn.click(
403
- fn=lambda eq_count: add_equation(substrate_equations, eq_count),
404
- inputs=substrate_eq_count,
405
- outputs=[*[row for row, _ in substrate_equations], substrate_eq_count]
406
- )
407
- remove_substrate_btn.click(
408
- fn=lambda eq_count: remove_equation(substrate_equations, eq_count),
409
- inputs=substrate_eq_count,
410
- outputs=[*[row for row, _ in substrate_equations], substrate_eq_count]
411
- )
412
-
413
- add_product_btn.click(
414
- fn=lambda eq_count: add_equation(product_equations, eq_count),
415
- inputs=product_eq_count,
416
- outputs=[*[row for row, _ in product_equations], product_eq_count]
417
- )
418
- remove_product_btn.click(
419
- fn=lambda eq_count: remove_equation(product_equations, eq_count),
420
- inputs=product_eq_count,
421
- outputs=[*[row for row, _ in product_equations], product_eq_count]
422
- )
423
-
424
- simulate_inputs = [
425
- file_input,
426
- *[eq_input for row, eq_input in biomass_equations],
427
- *biomass_params,
428
- *biomass_bounds,
429
- *[eq_input for row, eq_input in substrate_equations],
430
- *substrate_params,
431
- *substrate_bounds,
432
- *[eq_input for row, eq_input in product_equations],
433
- *product_params,
434
- *product_bounds,
435
- legend_position,
436
- show_legend,
437
- show_params,
438
- biomass_eq_count,
439
- substrate_eq_count,
440
- product_eq_count
441
- ]
442
-
443
- simulate_btn.click(
444
- fn=process_and_plot,
445
- inputs=simulate_inputs,
446
- outputs=[output_gallery, analysis_output]
447
- )
448
 
449
- return demo
 
450
 
 
451
  if __name__ == "__main__":
452
  demo = create_interface()
453
  demo.launch()
 
12
  from sympy import symbols, sympify, lambdify
13
  import copy
14
  from config import DEVICE, MODEL_PATH, MAX_LENGTH, TEMPERATURE
 
15
 
16
+ # Configuración del dispositivo
17
  device = DEVICE
18
+
19
+ # Cargar el modelo
20
+ model_path = MODEL_PATH # Reemplaza con la ruta real de tu modelo
21
  tokenizer = AutoTokenizer.from_pretrained(model_path)
22
+ model = AutoModelForCausalLM.from_pretrained(model_path)
23
+ model.to(device)
24
+ model.eval()
25
 
26
+ @torch.no_grad()
27
  def generate_analysis(prompt, max_length=MAX_LENGTH):
28
  try:
29
  input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
30
+ max_gen_length = min(max_length + input_ids.size(1), model.config.max_position_embeddings)
31
+
32
  generated_ids = model.generate(
33
  input_ids=input_ids,
34
+ max_length=max_gen_length,
35
  temperature=TEMPERATURE,
36
  num_return_sequences=1,
37
  no_repeat_ngram_size=2,
38
  early_stopping=True
39
  )
40
+
41
  output_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
42
  analysis = output_text[len(prompt):].strip()
43
  return analysis
44
  except Exception as e:
45
+ return f"Ocurrió un error durante el análisis: {e}"
46
 
47
  def parse_bounds(bounds_str, num_params):
48
  try:
 
57
  upper_bounds = [np.inf] * num_params
58
  return lower_bounds, upper_bounds
59
 
60
+ # Aquí incluye la función process_and_plot completa, asegurándote de que no haya referencias a decorators o @spaces.GPU
61
+
62
  def process_and_plot(
63
  file,
64
+ # Lista completa de parámetros según tu código
65
+ # Asegúrate de que coincida con los inputs en UI.py
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  ):
67
+ # Implementación de la función process_and_plot
68
+ # Procesa los datos, ajusta los modelos, genera las gráficas y el análisis
69
+ pass # Reemplaza con tu implementación
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ # Importar la función create_interface desde UI.py
72
+ from UI import create_interface
73
 
74
+ # Si deseas ejecutar la interfaz desde este archivo, asegúrate de que este bloque no cause conflictos al importar
75
  if __name__ == "__main__":
76
  demo = create_interface()
77
  demo.launch()