baxin commited on
Commit
7cda317
·
verified ·
1 Parent(s): a20ad5f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +74 -97
main.py CHANGED
@@ -1,104 +1,81 @@
1
- import gradio as gr
2
- import requests
3
- import uuid
4
  import os
 
 
 
5
 
6
- def string_to_binary(input_string):
7
- binary_string = ''.join(format(ord(char), '08b') for char in input_string)
8
- return binary_string
9
-
10
-
11
- def upload_protocol(protocol_name):
12
- robot_ip = "localhost"
13
- # robot_url = "https://baxin-ot-analysis.hf.space"
14
- endpoint = f"http://{robot_ip}:31950/protocols"
15
- # protocol_name = generate_unique_name()
16
-
17
- protocol_file = open(protocol_name, "rb")
18
- files = {
19
- "files": (protocol_name, protocol_file),
20
- }
21
-
22
-
23
- headers = {"Opentrons-Version": "3"}
24
- response = requests.post(endpoint, headers=headers, files=files)
25
- response_data = response.json()
26
-
27
- protocol_file.close()
28
- if os.path.exists(protocol_name):
29
- # if the protocol file is existing, remove it
30
- os.remove(protocol_name)
31
-
32
- if 'data' in response_data:
33
- response_data = response.json()
34
- protocol_id = response_data["data"]["id"]
35
- analysis_result=response_data["data"]["analyses"]
36
- analysis_id = response_data["data"]["analysisSummaries"][0]["id"]
37
- analysis_status = response_data["data"]["analysisSummaries"][0]["status"]
38
- print(protocol_id)
39
- print(analysis_result)
40
- print(analysis_id)
41
- print(analysis_status)
42
- return f"success\n protocol_id:{protocol_id}\n analysis_id:{analysis_id}"
43
- else:
44
- print("analysis error")
45
- error_id = response_data["errors"][0]['id']
46
- error_code = response_data["errors"][0]["errorCode"]
47
- error_detail = response_data["errors"][0]['detail']
48
- print(error_id)
49
- print(error_code)
50
- print(error_detail)
51
- return f"{error_id}\n{error_code}\n{error_detail}"
52
-
53
- def generate_unique_name():
54
- unique_name = str(uuid.uuid4()) + ".py"
55
- return unique_name
56
-
57
- def send_post_request(payload):
58
- url = "https://baxin-simulator.hf.space/protocol"
59
- protocol_name = generate_unique_name()
60
- data = {"name": protocol_name, "content": payload}
61
- headers = {"Content-Type": "application/json"}
62
-
63
- response = requests.post(url, json=data, headers=headers)
64
-
65
- if response.status_code != 200:
66
- print("Error: " + response.text)
67
- return "Error: " + response.text
68
-
69
- # Check the response before returning it
70
- response_data = response.json()
71
- if "error_message" in response_data:
72
- print("Error in response:", response_data["error_message"])
73
- return response_data["error_message"]
74
- elif "protocol_name" in response_data:
75
- print("Protocol executed successfully. Run log:", response_data["run_log"])
76
- return response_data["run_log"]
77
- else:
78
- print("Unexpected response:", response_data)
79
- return "Unexpected response"
80
-
81
-
82
-
83
-
84
- def send_message(text, chatbot):
85
- # Send POST request and get response
86
- # response = send_post_request(text)
87
- # binary_protocol = string_to_binary(text)
88
- protocol_name = generate_unique_name()
89
- with open(protocol_name, "w") as file:
90
- file.write(text)
91
-
92
- response = upload_protocol(protocol_name)
93
- # Update chatbot with response
94
- chatbot.append(("opentrons analysis result", response))
95
- return chatbot
96
 
97
  with gr.Blocks() as app:
98
- textbox = gr.Textbox()
99
- send_button = gr.Button(value="Send")
100
- chatbot = gr.Chatbot()
 
101
  clear_button = gr.ClearButton([textbox, chatbot])
 
102
  send_button.click(send_message, [textbox, chatbot], [chatbot])
 
103
 
104
- app.launch()
 
 
 
 
 
1
  import os
2
+ import tempfile
3
+ import requests
4
+ import gradio as gr
5
 
6
+ ROBOT_IP = os.getenv("ROBOT_IP", "localhost")
7
+ ROBOT_PORT = int(os.getenv("ROBOT_PORT", "31950"))
8
+ OT_API_VERSION = os.getenv("OT_API_VERSION", "3")
9
+ TIMEOUT_SEC = float(os.getenv("HTTP_TIMEOUT", "30"))
10
+
11
+ def upload_protocol_file(filepath: str) -> str:
12
+ endpoint = f"http://{ROBOT_IP}:{ROBOT_PORT}/protocols"
13
+ headers = {"Opentrons-Version": OT_API_VERSION}
14
+ filename = os.path.basename(filepath)
15
+
16
+ try:
17
+ with open(filepath, "rb") as f:
18
+ files = {"files": (filename, f, "text/x-python")}
19
+ resp = requests.post(endpoint, headers=headers, files=files, timeout=TIMEOUT_SEC)
20
+ except requests.RequestException as e:
21
+ return f"HTTP error: {e}"
22
+
23
+ try:
24
+ data = resp.json()
25
+ except ValueError:
26
+ return f"Non-JSON response (status={resp.status_code}):\n{resp.text[:1000]}"
27
+
28
+ if resp.status_code >= 400:
29
+ if isinstance(data, dict) and data.get("errors"):
30
+ err = data["errors"][0]
31
+ return (
32
+ f"Upload failed (HTTP {resp.status_code})\n"
33
+ f"id: {err.get('id')}\n"
34
+ f"code: {err.get('errorCode')}\n"
35
+ f"detail: {err.get('detail')}"
36
+ )
37
+ return f"Upload failed (HTTP {resp.status_code}):\n{data}"
38
+
39
+ if isinstance(data, dict) and "data" in data:
40
+ d = data["data"]
41
+ summaries = d.get("analysisSummaries") or []
42
+ return (
43
+ "✅ success\n"
44
+ f"protocol_id: {d.get('id')}\n"
45
+ f"analysis_id: {(summaries[0].get('id') if summaries else None)}\n"
46
+ f"analysis_status: {(summaries[0].get('status') if summaries else None)}"
47
+ )
48
+
49
+ return f"Unexpected response:\n{data}"
50
+
51
+ def send_message(text, history):
52
+ text = (text or "").strip()
53
+ if not text:
54
+ return history
55
+
56
+ fd, path = tempfile.mkstemp(prefix="protocol_", suffix=".py")
57
+ try:
58
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
59
+ f.write(text)
60
+ result = upload_protocol_file(path)
61
+ finally:
62
+ try:
63
+ os.remove(path)
64
+ except OSError:
65
+ pass
66
+
67
+ history.append((text, result))
68
+ return history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  with gr.Blocks() as app:
71
+ gr.Markdown("## Opentrons Protocol Analyzer")
72
+ textbox = gr.Textbox(lines=12, label="Paste protocol Python code")
73
+ send_button = gr.Button(value="Analyze")
74
+ chatbot = gr.Chatbot(label="Results")
75
  clear_button = gr.ClearButton([textbox, chatbot])
76
+
77
  send_button.click(send_message, [textbox, chatbot], [chatbot])
78
+ textbox.submit(send_message, [textbox, chatbot], [chatbot]) # Enterでも送信
79
 
80
+ if __name__ == "__main__":
81
+ app.launch(server_name="0.0.0.0", server_port=7860)