Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,69 +1,52 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
# lone github repro & add to sys paths
|
5 |
-
import gradio as gr
|
6 |
-
|
7 |
-
import os
|
8 |
-
|
9 |
-
import requests
|
10 |
-
|
11 |
-
from specklepy.api.client import SpeckleClient
|
12 |
-
from specklepy.api.credentials import get_default_account, get_local_accounts
|
13 |
-
from specklepy.transports.server import ServerTransport
|
14 |
-
from specklepy.api import operations
|
15 |
-
from specklepy.objects.geometry import Polyline, Point
|
16 |
-
|
17 |
-
from huggingface_hub import webhook_endpoint, WebhookPayload
|
18 |
-
from fastapi import Request
|
19 |
-
|
20 |
-
import requests
|
21 |
-
import datetime
|
22 |
-
import json
|
23 |
-
|
24 |
-
|
25 |
-
# dictionary that collects tags that can be added to commit messages.
|
26 |
-
# key -> column name in notion
|
27 |
-
# value -> possible values
|
28 |
-
tag_dict = {"status-message":["WIP", "ReviewNeeded", "Final"]}
|
29 |
-
|
30 |
|
|
|
|
|
|
|
31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
def extract_branch_info(stream_id, server_url=None, token=None):
|
36 |
-
|
37 |
-
|
38 |
-
client.authenticate_with_token(token=token)
|
39 |
-
|
40 |
|
41 |
branches = client.branch.list(stream_id, 100)
|
42 |
-
|
43 |
branch_info = []
|
44 |
|
45 |
for branch in branches:
|
46 |
-
print (branch.name)
|
47 |
branch_data = {
|
48 |
"Name": branch.name,
|
49 |
"description": branch.description,
|
50 |
"url": f"{server_url}/streams/{stream_id}/branches/{branch.name.replace('/', '%2F').replace('+', '%2B')}"
|
51 |
-
|
52 |
}
|
53 |
|
54 |
-
# Determine sub-variant
|
55 |
-
#if branch.name.startswith(("template_geometry", "graph_geometry")):
|
56 |
-
if '+' in branch.name:
|
57 |
-
slash_index = branch.name.rfind('/')
|
58 |
-
plus_index = branch.name.find('+', slash_index)
|
59 |
-
sub_variant = branch.name[slash_index + 1:plus_index]
|
60 |
-
else:
|
61 |
-
sub_variant = "default"
|
62 |
-
branch_data["sub-variant"] = sub_variant
|
63 |
-
|
64 |
-
# Get commits for the branch
|
65 |
-
|
66 |
-
#try:
|
67 |
commits = client.branch.get(stream_id, branch.name).commits.items
|
68 |
if commits:
|
69 |
latest_commit = commits[0]
|
@@ -71,219 +54,23 @@ def extract_branch_info(stream_id, server_url=None, token=None):
|
|
71 |
branch_data["commit_url"] = f"{server_url}streams/{stream_id}/commits/{latest_commit.id}"
|
72 |
branch_data["commit_message"] = latest_commit.message
|
73 |
branch_data["author"] = latest_commit.authorName
|
74 |
-
# Check if the commit message contains '#+' and then extract tags
|
75 |
-
if '#+' in latest_commit.message:
|
76 |
-
tags_part = latest_commit.message.split("#+")[1]
|
77 |
-
branch_data["status-message"] = [tg for tg in tag_dict["status-message"] if tg in tags_part]
|
78 |
-
else:
|
79 |
-
branch_data["status-message"] = []
|
80 |
-
#except Exception as e:
|
81 |
-
# print(f"Error fetching commits for branch {branch.name}: {str(e)}")
|
82 |
-
|
83 |
branch_info.append(branch_data)
|
84 |
|
85 |
return branch_info
|
86 |
|
87 |
-
|
88 |
-
def update_select_options(database_id, headers, branch_names):
|
89 |
-
update_payload = {
|
90 |
-
"properties": {
|
91 |
-
"depends-on": {
|
92 |
-
"multi_select": {
|
93 |
-
"options": [{"name": name} for name in branch_names]
|
94 |
-
}
|
95 |
-
}
|
96 |
-
}
|
97 |
-
}
|
98 |
-
response = requests.patch(f"https://api.notion.com/v1/databases/{database_id}", headers=headers, json=update_payload)
|
99 |
-
response.raise_for_status()
|
100 |
-
|
101 |
-
def sync_to_notion(token, database_id, branch_data):
|
102 |
-
base_url = "https://api.notion.com/v1"
|
103 |
-
headers = {
|
104 |
-
"Authorization": f"Bearer {token}",
|
105 |
-
"Notion-Version": "2022-06-28",
|
106 |
-
"Content-Type": "application/json"
|
107 |
-
}
|
108 |
-
|
109 |
-
# Extract all branch names for the "depends-on" options
|
110 |
-
branch_names = [branch['Name'] for branch in branch_data]
|
111 |
-
# Update the "depends-on" multi-select options to match branch names
|
112 |
-
update_select_options(database_id, headers, branch_names)
|
113 |
-
|
114 |
-
try:
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
# Fetch existing data from Notion database
|
119 |
-
response = requests.post(f"{base_url}/databases/{database_id}/query", headers=headers)
|
120 |
-
response.raise_for_status()
|
121 |
-
pages = response.json().get('results', [])
|
122 |
-
|
123 |
-
# Create a dictionary for the latest update time of each branch
|
124 |
-
branch_details = {branch['Name']: {'updated': branch.get('updated', ''), 'commit_message': branch.get('commit_message', '')} for branch in branch_data}
|
125 |
-
|
126 |
-
|
127 |
-
# Status color mapping
|
128 |
-
status_colors = {
|
129 |
-
"outdated": "red",
|
130 |
-
"up-to-date": "green",
|
131 |
-
"empty": "gray"
|
132 |
-
}
|
133 |
-
|
134 |
-
# Process each branch and update or create Notion rows
|
135 |
-
|
136 |
-
print("branchData", branch_data)
|
137 |
-
for branch in branch_data:
|
138 |
-
# Find the corresponding page in Notion
|
139 |
-
branch_update_time = branch_details.get(branch['Name'], {}).get('updated', '')
|
140 |
-
|
141 |
-
page_id = None
|
142 |
-
existing_depends_on = []
|
143 |
-
for page in pages:
|
144 |
-
notion_name = page['properties']['Name']['title'][0]['text']['content'] if page['properties']['Name']['title'] else ''
|
145 |
-
if notion_name == branch['Name']:
|
146 |
-
page_id = page['id']
|
147 |
-
# Retain the existing value of "depends-on"
|
148 |
-
existing_depends_on = [dep['name'] for dep in page['properties'].get('depends-on', {}).get('multi_select', [])]
|
149 |
-
break
|
150 |
-
|
151 |
-
# Determine status based on dependencies
|
152 |
-
status_tag = "up-to-date" # Default status
|
153 |
-
for dependency_name in existing_depends_on:
|
154 |
-
dependency_info = branch_details.get(dependency_name, {})
|
155 |
-
branch_update_time = branch_details.get(branch['Name'], {}).get('updated', '')
|
156 |
-
|
157 |
-
# Check if the dependency is more recent and if its commit message does not contain 'isConnected'
|
158 |
-
if dependency_info.get('updated', '') > branch_update_time and "isConnected" not in dependency_info.get('commit_message', ''):
|
159 |
-
status_tag = "outdated"
|
160 |
-
break
|
161 |
-
|
162 |
-
# If there's no update information, set status to 'empty'
|
163 |
-
if not branch_update_time:
|
164 |
-
status_tag = "empty"
|
165 |
-
|
166 |
-
# Prepare data for updating or creating a page
|
167 |
-
print (branch.get("url", ""))
|
168 |
-
updated_value = branch.get("updated")
|
169 |
-
|
170 |
-
if isinstance(updated_value, datetime.datetime): # Use datetime.datetime here
|
171 |
-
updated_isoformat = updated_value.isoformat()
|
172 |
-
else:
|
173 |
-
updated_isoformat = datetime.datetime.now().isoformat() # Use datetime.datetime.now() here
|
174 |
-
# Prepare status-message tags for multi-select
|
175 |
-
status_messages = branch.get("status-message", [])
|
176 |
-
status_message_data = [{"name": sm} for sm in status_messages]
|
177 |
-
|
178 |
-
url_clean = branch.get("url", "")
|
179 |
-
url_clean = url_clean.replace("xyz//","xyz/")
|
180 |
-
page_data = {
|
181 |
-
"properties": {
|
182 |
-
"Name": {"title": [{"text": {"content": branch['Name']}}]},
|
183 |
-
"status-tag": {"select": {"name": status_tag}}, # Assuming 'select' type
|
184 |
-
"status": {"rich_text": [{"text": {"content": "Status: " + status_tag}}]},
|
185 |
-
"url": {"url": url_clean},
|
186 |
-
"updated": {"date": {"start": updated_isoformat}},
|
187 |
-
"description": {"rich_text": [{"text": {"content": str(branch.get("description", ""))}}]},
|
188 |
-
"sub-variant": {"rich_text": [{"text": {"content": branch.get("sub-variant", "")}}]},
|
189 |
-
"author": {"rich_text": [{"text": {"content": branch.get("author", "")}}]},
|
190 |
-
"commit_message": {"rich_text": [{"text": {"content": branch.get("commit_message", "")}}]},
|
191 |
-
"depends-on": {"multi_select": [{"name": d} for d in existing_depends_on]},
|
192 |
-
"status-message": {"multi_select": status_message_data}
|
193 |
-
}
|
194 |
-
}
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
# Update an existing page or create a new one
|
199 |
-
if page_id:
|
200 |
-
update_url = f"{base_url}/pages/{page_id}"
|
201 |
-
response = requests.patch(update_url, headers=headers, data=json.dumps(page_data))
|
202 |
-
else:
|
203 |
-
create_page_data = {
|
204 |
-
"parent": {"database_id": database_id},
|
205 |
-
**page_data
|
206 |
-
}
|
207 |
-
response = requests.post(f"{base_url}/pages", headers=headers, data=json.dumps(create_page_data))
|
208 |
-
|
209 |
-
response.raise_for_status()
|
210 |
-
|
211 |
-
print("Data synced to Notion successfully.")
|
212 |
-
|
213 |
-
except requests.exceptions.HTTPError as errh:
|
214 |
-
print("Http Error:", errh)
|
215 |
-
except requests.exceptions.ConnectionError as errc:
|
216 |
-
print("Error Connecting:", errc)
|
217 |
-
except requests.exceptions.Timeout as errt:
|
218 |
-
print("Timeout Error:", errt)
|
219 |
-
except requests.exceptions.RequestException as err:
|
220 |
-
print("Something went wrong", err)
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
# Predefined dictionaries of streams to update
|
228 |
-
streams = {
|
229 |
-
"2B_100_batch": {
|
230 |
-
"stream": "287b605243",
|
231 |
-
"notionDB": '402d60c9c1ef4980a3d85c5a4f4a0c97'
|
232 |
-
},
|
233 |
-
"2B_U100_batch": {
|
234 |
-
"stream": "ebcfc50abe",
|
235 |
-
"notionDB": '00c3a26a119f487fa028c1ed404f22ba'
|
236 |
-
}
|
237 |
-
}
|
238 |
-
|
239 |
-
# Function to run on button click
|
240 |
-
@webhook_endpoint # Define a unique endpoint URL
|
241 |
async def update_streams(request: Request):
|
242 |
-
# Read the request body as JSON
|
243 |
payload = await request.json()
|
244 |
-
|
245 |
-
print(str(payload))
|
246 |
-
|
247 |
-
|
248 |
-
# Accessing nested data in the 'event' object
|
249 |
-
|
250 |
-
speckle_token = os.environ.get("SPECKLE_TOKEN")
|
251 |
-
notion_token = os.environ.get("NOTION_TOKEN")
|
252 |
-
|
253 |
-
#client = SpeckleClient(host="https://speckle.xyz")
|
254 |
-
#client.authenticate_with_token(token=speckle_token)
|
255 |
-
|
256 |
-
|
257 |
|
258 |
if 'payload' in payload and 'stream' in payload['payload']:
|
259 |
stream_info = payload['payload']['stream']
|
260 |
-
if '
|
261 |
-
|
262 |
-
print("
|
263 |
-
# retrieve specific stream
|
264 |
-
stream_id = streams[stream_name]["stream"]
|
265 |
-
notion_db = streams[stream_name]["notionDB"]
|
266 |
-
branch_data = extract_branch_info(stream_id, server_url="https://speckle.xyz/", token=speckle_token)
|
267 |
-
sync_to_notion(notion_token, notion_db, branch_data)
|
268 |
-
else:
|
269 |
-
print("updating data for all streams")
|
270 |
-
for key, value in streams.items():
|
271 |
-
stream_id = value["stream"]
|
272 |
-
notion_db = value["notionDB"]
|
273 |
-
|
274 |
-
branch_data = extract_branch_info(stream_id, server_url="https://speckle.xyz/", token=speckle_token)
|
275 |
-
sync_to_notion(notion_token, notion_db, branch_data)
|
276 |
-
|
277 |
-
return "All streams updated successfully!"
|
278 |
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
fn=update_streams,
|
283 |
-
inputs=gr.components.Button(value="Update Streams"),
|
284 |
-
outputs="text",
|
285 |
-
)
|
286 |
|
287 |
-
|
288 |
-
iface.launch()
|
289 |
-
"""
|
|
|
1 |
+
# Speckle stream and authentication information
|
2 |
+
speckle_token = os.getenv("SPECKLE_TOKEN")
|
3 |
+
speckle_server_url = "https://speckle.xyz/"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
# WebSocket URI
|
6 |
+
ws_uri = "wss://onlinewebsocketserver.onrender.com"
|
7 |
+
websocket = None
|
8 |
|
9 |
+
# Connect to WebSocket
|
10 |
+
async def connect():
|
11 |
+
global websocket
|
12 |
+
try:
|
13 |
+
websocket = await websockets.connect(ws_uri)
|
14 |
+
print("Connected to the WebSocket server")
|
15 |
+
except Exception as e:
|
16 |
+
print(f"Connection failed: {e}")
|
17 |
+
|
18 |
+
async def send_data(data):
|
19 |
+
global websocket
|
20 |
+
if websocket is None or websocket.closed:
|
21 |
+
await connect()
|
22 |
+
if websocket is None or websocket.closed:
|
23 |
+
print("Failed to connect to WebSocket server.")
|
24 |
+
return
|
25 |
|
26 |
+
try:
|
27 |
+
await websocket.send(json.dumps(data))
|
28 |
+
print(f"Sent: {data}")
|
29 |
+
response = await websocket.recv()
|
30 |
+
response_data = json.loads(response)
|
31 |
+
print(f"Received: {response_data}")
|
32 |
+
except Exception as e:
|
33 |
+
print(f"Failed to send or receive data: {e}")
|
34 |
+
websocket = None
|
35 |
|
36 |
def extract_branch_info(stream_id, server_url=None, token=None):
|
37 |
+
client = SpeckleClient(host=server_url)
|
38 |
+
client.authenticate_with_token(token=token)
|
|
|
|
|
39 |
|
40 |
branches = client.branch.list(stream_id, 100)
|
|
|
41 |
branch_info = []
|
42 |
|
43 |
for branch in branches:
|
|
|
44 |
branch_data = {
|
45 |
"Name": branch.name,
|
46 |
"description": branch.description,
|
47 |
"url": f"{server_url}/streams/{stream_id}/branches/{branch.name.replace('/', '%2F').replace('+', '%2B')}"
|
|
|
48 |
}
|
49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
commits = client.branch.get(stream_id, branch.name).commits.items
|
51 |
if commits:
|
52 |
latest_commit = commits[0]
|
|
|
54 |
branch_data["commit_url"] = f"{server_url}streams/{stream_id}/commits/{latest_commit.id}"
|
55 |
branch_data["commit_message"] = latest_commit.message
|
56 |
branch_data["author"] = latest_commit.authorName
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
branch_info.append(branch_data)
|
58 |
|
59 |
return branch_info
|
60 |
|
61 |
+
@webhook_endpoint
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
async def update_streams(request: Request):
|
|
|
63 |
payload = await request.json()
|
64 |
+
print(f"Received webhook payload: {payload}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
if 'payload' in payload and 'stream' in payload['payload']:
|
67 |
stream_info = payload['payload']['stream']
|
68 |
+
if 'id' in stream_info:
|
69 |
+
stream_id = stream_info['id']
|
70 |
+
print(f"Fetching data for stream: {stream_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
+
# Extract branch info and send it via WebSocket
|
73 |
+
branch_data = extract_branch_info(stream_id, server_url=speckle_server_url, token=speckle_token)
|
74 |
+
await send_data(branch_data)
|
|
|
|
|
|
|
|
|
75 |
|
76 |
+
return "All streams updated successfully!"
|
|
|
|