baxin commited on
Commit
0145d3c
·
verified ·
1 Parent(s): e25c15e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -43
app.py CHANGED
@@ -2,60 +2,94 @@ import gradio as gr
2
  import requests
3
  import uuid
4
  import os
 
 
 
 
 
 
5
 
6
  def generate_unique_name():
7
- unique_name = str(uuid.uuid4()) + ".py"
8
- return unique_name
 
 
 
9
 
10
- def send_post_request(payload):
11
- url = "https://baxin-simulator.hf.space/simulate"
12
- token = os.environ['HF_TOKEN']
13
  protocol_name = generate_unique_name()
14
- data = {"name": protocol_name, "content": payload}
15
- headers = {"Content-Type": "application/json", 'Authorization': 'Bearer {}'.format(token)}
16
-
17
- response = requests.post(url, json=data, headers=headers)
18
-
19
- if response.status_code != 200:
20
- print("Error: " + response.text)
21
- return "Error: " + response.text
22
-
23
- # Check the response before returning it
24
- # ToDo clean up code
25
- response_data = response.json()
26
- if "error_message" in response_data:
27
- print("Error in response:", response_data["error_message"])
28
- return response_data["error_message"]
29
- elif "protocol_name" in response_data:
30
- # print("Protocol executed successfully. Run log:", response_data["run_log"])
31
 
32
- return response_data["run_status"]
33
- # ToDo if run_log option is on
34
- # return response_data["run_log"]
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- else:
37
- print("Unexpected response:", response_data)
38
- return "Unexpected response"
39
 
40
- def send_message(text, chatbot):
41
- # Send POST request and get response
42
- response = send_post_request(text)
43
- # Update chatbot with response
44
- chatbot.append(("opentrons_simulator result", response))
45
- return chatbot
46
 
 
47
  title = """
48
  <div align="center">
49
- # OT-2 Simulator: Emulating Opentrons Protocols with Python API
50
-
51
  </div>
52
  """
53
- with gr.Blocks() as app:
 
54
  gr.Markdown(title)
55
- textbox = gr.Textbox(label="Enter protocol")
56
- send_button = gr.Button(value="Send")
57
- chatbot = gr.Chatbot()
58
- clear_button = gr.ClearButton([textbox, chatbot])
59
- send_button.click(send_message, [textbox, chatbot], [chatbot])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- app.launch()
 
2
  import requests
3
  import uuid
4
  import os
5
+ import json
6
+
7
+
8
+ HF_TOKEN = os.environ.get("HF_TOKEN")
9
+
10
+ API_URL = "https://baxin-simulator.hf.space/simulate"
11
 
12
  def generate_unique_name():
13
+ return f"protocol_{uuid.uuid4().hex[:8]}.py"
14
+
15
+ def simulate_protocol(protocol_content: str):
16
+ if not HF_TOKEN:
17
+ return "Error: HF_TOKEN is not set. Please set it in your environment variables."
18
 
 
 
 
19
  protocol_name = generate_unique_name()
20
+
21
+ headers = {
22
+ "Content-Type": "application/json",
23
+ "Authorization": f"Bearer {HF_TOKEN}"
24
+ }
25
+
26
+ data = {
27
+ "name": protocol_name,
28
+ "content": protocol_content
29
+ }
30
+
31
+ try:
32
+ response = requests.post(API_URL, json=data, headers=headers, timeout=60)
 
 
 
 
33
 
34
+ if response.status_code == 200:
35
+ response_data = response.json()
36
+ return response_data.get("run_log", "Success, but no run log was returned.")
37
+ else:
38
+ try:
39
+ error_data = response.json()
40
+ detail = error_data.get("detail", {})
41
+ if isinstance(detail, dict):
42
+ error_message = detail.get('error_details', response.text)
43
+ else:
44
+ error_message = detail
45
+ return f"API Error (Status {response.status_code}):\n\n{error_message}"
46
+ except json.JSONDecodeError:
47
+ return f"API Error (Status {response.status_code}):\n\n{response.text}"
48
 
49
+ except requests.exceptions.RequestException as e:
50
+ return f"Network Error: Failed to connect to the API.\n\n{e}"
 
51
 
52
+ def add_to_chatbot(protocol_text: str, chat_history: list):
53
+ chat_history.append((protocol_text, None))
54
+ response = simulate_protocol(protocol_text)
55
+ chat_history.append((None, response))
56
+ return chat_history
 
57
 
58
+ # --- Gradio UI ---
59
  title = """
60
  <div align="center">
61
+ <h1>OT-2 Simulator</h1>
62
+ <p>Enter your Opentrons protocol code below and click 'Send' to run the simulation.</p>
63
  </div>
64
  """
65
+
66
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
67
  gr.Markdown(title)
68
+
69
+ with gr.Row():
70
+ chatbot = gr.Chatbot(
71
+ label="Simulation Log",
72
+ bubble_full_width=True,
73
+ height=500
74
+ )
75
+
76
+ with gr.Row():
77
+ textbox = gr.Textbox(
78
+ label="Enter your protocol here",
79
+ placeholder="from opentrons import protocol_api\n\nmetadata = {'apiLevel': '2.11'}\n\ndef run(protocol: protocol_api.ProtocolContext):\n tiprack = protocol.load_labware('opentrons_96_tiprack_300ul', 1)\n p300 = protocol.load_instrument('p300_single_gen2', 'right', tip_racks=[tiprack])\n p300.pick_up_tip()\n p300.drop_tip()",
80
+ lines=15,
81
+ scale=4,
82
+ )
83
+
84
+ with gr.Row():
85
+ send_button = gr.Button("▶️ Run Simulation", variant="primary")
86
+ clear_button = gr.ClearButton([textbox, chatbot], value="🗑️ Clear")
87
+
88
+ # ボタンがクリックされたときの動作を定義
89
+ send_button.click(
90
+ fn=add_to_chatbot,
91
+ inputs=[textbox, chatbot],
92
+ outputs=[chatbot]
93
+ )
94
 
95
+ app.launch()