Spaces:
Runtime error
Runtime error
Update app.py
Browse files4 unmodified lines567891011121314151617182 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402418 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882894 unmodified linesimport gradio as grimport osimport requestsfrom specklepy.api.client import SpeckleClientfrom specklepy.api.credentials import get_default_account, get_local_accountsfrom specklepy.transports.server import ServerTransportfrom specklepy.api import operationsfrom specklepy.objects.geometry import Polyline, Pointfrom huggingface_hub import webhook_endpoint, WebhookPayloadfrom fastapi import Request2 unmodified linesimport datetimeimport json# dictionary that collects tags that can be added to commit messages.# key -> column name in notion# value -> possible valuestag_dict = {"status-message":["WIP", "ReviewNeeded", "Final"]}# tag part seperator -> #+ , other_tagsdef extract_branch_info(stream_id, server_url=None, token=None):if server_url and token:client = SpeckleClient(host=server_url)client.authenticate_with_token(token=token)branches = client.branch.list(stream_id, 100)branch_info = []for branch in branches:print (branch.name)branch_data = {"Name": branch.name,"description": branch.description,"url": f"{server_url}/streams/{stream_id}/branches/{branch.name.replace('/', '%2F').replace('+', '%2B')}"}# Determine sub-variant#if branch.name.startswith(("template_geometry", "graph_geometry")):if '+' in branch.name:slash_index = branch.name.rfind('/')plus_index = branch.name.find('+', slash_index)sub_variant = branch.name[slash_index + 1:plus_index]else:sub_variant = "default"branch_data["sub-variant"] = sub_variant# Get commits for the branch#try:commits = client.branch.get(stream_id, branch.name).commits.itemsif commits:latest_commit = commits[0]branch_data["updated"] = latest_commit.createdAtbranch_data["commit_url"] = f"{server_url}streams/{stream_id}/commits/{latest_commit.id}"branch_data["commit_message"] = latest_commit.messagebranch_data["author"] = latest_commit.authorName# Check if the commit message contains '#+' and then extract tagsif '#+' in latest_commit.message:tags_part = latest_commit.message.split("#+")[1]branch_data["status-message"] = [tg for tg in tag_dict["status-message"] if tg in tags_part]else:branch_data["status-message"] = []#except Exception as e:# print(f"Error fetching commits for branch {branch.name}: {str(e)}")branch_info.append(branch_data)return branch_infodef update_select_options(database_id, headers, branch_names):update_payload = {"properties": {"depends-on": {"multi_select": {"options": [{"name": name} for name in branch_names]}}}}response = requests.patch(f"https://api.notion.com/v1/databases/{database_id}", headers=headers, json=update_payload)response.raise_for_status()def sync_to_notion(token, database_id, branch_data):base_url = "https://api.notion.com/v1"headers = {"Authorization": f"Bearer {token}","Notion-Version": "2022-06-28","Content-Type": "application/json"}# Extract all branch names for the "depends-on" optionsbranch_names = [branch['Name'] for branch in branch_data]# Update the "depends-on" multi-select options to match branch namesupdate_select_options(database_id, headers, branch_names)try:# Fetch existing data from Notion databaseresponse = requests.post(f"{base_url}/databases/{database_id}/query", headers=headers)response.raise_for_status()pages = response.json().get('results', [])# Create a dictionary for the latest update time of each branchbranch_details = {branch['Name']: {'updated': branch.get('updated', ''), 'commit_message': branch.get('commit_message', '')} for branch in branch_data}# Status color mappingstatus_colors = {"outdated": "red","up-to-date": "green","empty": "gray"}# Process each branch and update or create Notion rowsprint("branchData", branch_data)for branch in branch_data:# Find the corresponding page in Notionbranch_update_time = branch_details.get(branch['Name'], {}).get('updated', '')page_id = Noneexisting_depends_on = []for page in pages:notion_name = page['properties']['Name']['title'][0]['text']['content'] if page['properties']['Name']['title'] else ''if notion_name == branch['Name']:page_id = page['id']# Retain the existing value of "depends-on"existing_depends_on = [dep['name'] for dep in page['properties'].get('depends-on', {}).get('multi_select', [])]break# Determine status based on dependenciesstatus_tag = "up-to-date" # Default statusfor dependency_name in existing_depends_on:dependency_info = branch_details.get(dependency_name, {})branch_update_time = branch_details.get(branch['Name'], {}).get('updated', '')# Check if the dependency is more recent and if its commit message does not contain 'isConnected'if dependency_info.get('updated', '') > branch_update_time and "isConnected" not in dependency_info.get('commit_message', ''):status_tag = "outdated"break# If there's no update information, set status to 'empty'if not branch_update_time:status_tag = "empty"# Prepare data for updating or creating a pageprint (branch.get("url", ""))updated_value = branch.get("updated")if isinstance(updated_value, datetime.datetime): # Use datetime.datetime hereupdated_isoformat = updated_value.isoformat()else:updated_isoformat = datetime.datetime.now().isoformat() # Use datetime.datetime.now() here# Prepare status-message tags for multi-selectstatus_messages = branch.get("status-message", [])status_message_data = [{"name": sm} for sm in status_messages]url_clean = branch.get("url", "")url_clean = url_clean.replace("xyz//","xyz/")page_data = {"properties": {"Name": {"title": [{"text": {"content": branch['Name']}}]},"status-tag": {"select": {"name": status_tag}}, # Assuming 'select' type"status": {"rich_text": [{"text": {"content": "Status: " + status_tag}}]},"url": {"url": url_clean},"updated": {"date": {"start": updated_isoformat}},"description": {"rich_text": [{"text": {"content": str(branch.get("description", ""))}}]},"sub-variant": {"rich_text": [{"text": {"content": branch.get("sub-variant", "")}}]},"author": {"rich_text": [{"text": {"content": branch.get("author", "")}}]},"commit_message": {"rich_text": [{"text": {"content": branch.get("commit_message", "")}}]},"depends-on": {"multi_select": [{"name": d} for d in existing_depends_on]},"status-message": {"multi_select": status_message_data}}}# Update an existing page or create a new oneif page_id:update_url = f"{base_url}/pages/{page_id}"response = requests.patch(update_url, headers=headers, data=json.dumps(page_data))else:create_page_data = {"parent": {"database_id": database_id},**page_data}response = requests.post(f"{base_url}/pages", headers=headers, data=json.dumps(create_page_data))response.raise_for_status()print("Data synced to Notion successfully.")except requests.exceptions.HTTPError as errh:print("Http Error:", errh)except requests.exceptions.ConnectionError as errc:print("Error Connecting:", errc)except requests.exceptions.Timeout as errt:print("Timeout Error:", errt)except requests.exceptions.RequestException as err:print("Something went wrong", err)# Predefined dictionaries of streams to updatestreams = {"2B_100_batch": {"stream": "287b605243","notionDB": '402d60c9c1ef4980a3d85c5a4f4a0c97'},"2B_U100_batch": {"stream": "ebcfc50abe","notionDB": '00c3a26a119f487fa028c1ed404f22ba'}}# Function to run on button click@webhook_endpoint # Define a unique endpoint URLasync def update_streams(request: Request):8 unmodified linesspeckle_token = os.environ.get("SPECKLE_TOKEN")notion_token = os.environ.get("NOTION_TOKEN")#client = SpeckleClient(host="https://speckle.xyz")#client.authenticate_with_token(token=speckle_token)if 'payload' in payload and 'stream' in payload['payload']:stream_info = payload['payload']['stream']if 'name' in stream_info:stream_name = stream_info['name']print("update dat for: " + stream_name)# retrieve specific streamstream_id = streams[stream_name]["stream"]notion_db = streams[stream_name]["notionDB"]branch_data = extract_branch_info(stream_id, server_url="https://speckle.xyz/", token=speckle_token)sync_to_notion(notion_token, notion_db, branch_data)else:print("updating data for all streams")for key, value in streams.items():stream_id = value["stream"]notion_db = value["notionDB"]branch_data = extract_branch_info(stream_id, server_url="https://speckle.xyz/", token=speckle_token)sync_to_notion(notion_token, notion_db, branch_data)return "All streams updated successfully!""""# Create Gradio interfaceiface = gr.Interface(fn=update_streams,inputs=gr.components.Button(value="Update Streams"),outputs="text",)# Launch the appiface.launch()"""4 unmodified lines56789101112131415162 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502518 unmodified lines2602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403414 unmodified linesimport gradio as grimport osimport sysimport timeimport copyimport requestsfrom notion_client import Clientfrom huggingface_hub import webhook_endpoint, WebhookPayloadfrom fastapi import Request2 unmodified linesimport datetimeimport jsondef get_database_properties_overview(database_pages):# Iterate through the results (each page corresponds to a row in the database)for page in database_pages:print(f"Page ID: {page['id']}")# Print the name and type of each property in this pagefor prop_name, prop_data in page['properties'].items():prop_type = prop_data['type']print(f"Property Name: {prop_name}, Property Type: {prop_type}")break# query full databasedef fetch_all_database_pages(client, database_id):"""Fetches all pages from a specified Notion database.:param client: Initialized Notion client.:param database_id: The ID of the Notion database to query.:return: A list containing all pages from the database."""start_cursor = Noneall_pages = []while True:response = client.databases.query(**{"database_id": database_id,"start_cursor": start_cursor})all_pages.extend(response['results'])# Check if there's more data to fetchif response['has_more']:start_cursor = response['next_cursor']else:breakreturn all_pagesdef get_property_value(page, property_name):"""Extracts the value from a specific property in a Notion page based on its type.:param page: The Notion page data as retrieved from the API.:param property_name: The name of the property whose value is to be fetched.:return: The value or values contained in the specified property, depending on type."""# Check if the property exists in the pageif property_name not in page['properties']:return None # or raise an error if you preferproperty_data = page['properties'][property_name]prop_type = property_data['type']# Handle 'title' and 'rich_text' typesif prop_type in ['title', 'rich_text']:return ''.join(text_block['text']['content'] for text_block in property_data[prop_type])# Handle 'number' typeelif prop_type == 'number':return property_data[prop_type]# Handle 'select' typeelif prop_type == 'select':return property_data[prop_type]['name'] if property_data[prop_type] else None# Handle 'multi_select' typeelif prop_type == 'multi_select':return [option['name'] for option in property_data[prop_type]]# Handle 'date' typeelif prop_type == 'date':if property_data[prop_type]['end']:return (property_data[prop_type]['start'], property_data[prop_type]['end'])else:return property_data[prop_type]['start']# Handle 'relation' typeelif prop_type == 'relation':return [relation['id'] for relation in property_data[prop_type]]# Handle 'people' typeelif prop_type == 'people':return [person['name'] for person in property_data[prop_type] if 'name' in person]# Add more handlers as needed for other property typeselse:# Return None or raise an error for unsupported property typesreturn Nonedef replace_property_value(page, property_name, new_value):"""Replaces the value of a specified property in a Notion page object.:param page: The Notion page object.:param property_name: The name of the property to replace.:param new_value: The new value to set for the property."""if property_name not in page['properties']:raise ValueError(f"Property '{property_name}' not found in the page.")prop_type = page['properties'][property_name]['type']# Handle 'rich_text' and 'title' typesif prop_type in ['rich_text', 'title']:page['properties'][property_name][prop_type] = [{'text': {'content': new_value}}]# Handle 'number' typeelif prop_type == 'number':page['properties'][property_name][prop_type] = new_value# Handle 'select' typeelif prop_type == 'select':page['properties'][property_name][prop_type] = {'name': new_value}# Handle 'multi_select' type (assuming new_value is a list of strings)elif prop_type == 'multi_select':page['properties'][property_name][prop_type] = [{'name': val} for val in new_value]# Handle 'date' typeelif prop_type == 'date':page['properties'][property_name][prop_type] = {'start': new_value} # Assuming new_value is a date string# Handle 'checkbox' typeelif prop_type == 'checkbox':page['properties'][property_name][prop_type] = new_value # Assuming new_value is a boolean# Handle 'url' typeelif prop_type == 'url':page['properties'][property_name][prop_type] = new_value # Assuming new_value is a valid URL string# Handle 'email' typeelif prop_type == 'email':page['properties'][property_name][prop_type] = new_value # Assuming new_value is a valid email string# Add more handlers for other types as neededelse:raise NotImplementedError(f"Property type '{prop_type}' is not supported in this function.")def remove_property(page, property_name):"""Removes a specified property from a Notion page object.:param page: The Notion page object.:param property_name: The name of the property to remove.:return: The updated Notion page object."""if property_name in page['properties']:del page['properties'][property_name]else:raise ValueError(f"Property '{property_name}' not found in the page.")return pagedef check_and_update_or_create_page(notion, page_data, target_database_id, title_property_name):"""Checks if a page with the given title exists in the target database.If it does, updates the page; if not, creates a new page.:param notion: Notion client instance.:param page_data: Data for the page to create or update.:param target_database_id: ID of the target database.:param title_property_name: The name of the title property to check."""# Query the target database for a page with the same >> title <<query_filter = {"property": title_property_name,"title": {"equals": page_data['properties'][title_property_name]['title'][0]['text']['content']}}response = notion.databases.query(database_id=target_database_id, filter=query_filter)existing_pages = response.get('results', [])if existing_pages:# Page already exists, update itpage_id = existing_pages[0]['id']print(page_data['properties'])notion.pages.update(page_id=page_id, properties=page_data['properties'])else:# Page does not exist, create itnotion.pages.create(parent={"database_id": target_database_id}, properties=page_data['properties'])def get_page_by_id(notion_db_pages, page_id):for pg in notion_db_pages:if pg["id"] == page_id:return pgdef reset_database(notion, database_id):"""Resets a Notion database by archiving all its pages.Parameters:notion (Client): The Notion client instance.database_id (str): The ID of the database to reset."""def retrieve_all_pages():has_more = Truestart_cursor = Nonepages = []while has_more:response = notion.databases.query(**{"database_id": database_id, "start_cursor": start_cursor})pages.extend(response["results"])has_more = response["has_more"]start_cursor = response.get("next_cursor")return pagesdef delete_page(page_id):notion.pages.update(page_id, archived=True)pages = retrieve_all_pages()for page in pages:delete_page(page["id"])print(f"Reset of database {database_id} completed.")# Function to run on button click@webhook_endpoint # Define a unique endpoint URLasync def update_streams(request: Request):8 unmodified linesspeckle_token = os.environ.get("SPECKLE_TOKEN")notion_token = os.environ.get("NOTION_TOKEN")if continueFlag:name_mapper = {}name_mapperM = {}for page in lu_name_db["results"]:oriName = get_property_value(page, "name")shortName = get_property_value(page, "nameShort")medName = get_property_value(page, "nameMedium")name_mapper[oriName] = shortNamename_mapperM[oriName] = medName# Iterate through the results (each page corresponds to a row in the database)for page in database_pages:#check speckleAnalysisNamespeckName = get_property_value(page, "speckleName")shortName = get_property_value(page, "nameShort")longName = get_property_value(page, "nameLong")print(shortName)print(longName)subAttributes = get_property_value(page, "level_4")subAttributeFlag = Falseif len(subAttributes)>1:if subAttributes[0] != 'NA':subAttributeFlag = Truefor subAttr in subAttributes:# construct new page (speckleName, Name, longName, shortName, remove level_4)new_page = copy.deepcopy(page)speckName_full = speckName+subAttrif "#+" in shortName:shortestName = name_mapper.get(subAttr,subAttr)mediumName = name_mapperM.get(subAttr,subAttr)print("shortestName", shortestName, subAttr)shortName_full = shortName.replace("#+", shortestName)shortName_full.replace("DRT", "ART")#update short namereplace_property_value(new_page, "nameShort", shortName_full )if "#+" in longName:longName_full = longName.replace("#+", "::" +mediumName)longName_full = longName_full.replace(" ::", "::")longName_full = longName_full.replace(":: ", "::")longName_full.replace("DRT", "ART")#update long namereplace_property_value(new_page, "nameLong", longName_full )#update speckle name (-> as title column)replace_property_value(new_page, "name", speckName_full)# remove level_4 and speckleAnalysisNamenew_page = remove_property(new_page, "level_4")new_page = remove_property(new_page, "speckleName")new_page = remove_property(new_page, "Items")# update target database in notioncheck_and_update_or_create_page(notion, new_page, target_db, "name")if subAttributeFlag == False:# forward pagenew_page = copy.deepcopy(page)replace_property_value(new_page, "name", speckName)new_page = remove_property(new_page, "level_4")new_page = remove_property(new_page, "speckleName")new_page = remove_property(new_page, "Items")# update target database in notionprint(get_property_value(new_page, "nameLong"))check_and_update_or_create_page(notion, new_page, target_db, "name")return "All streams updated successfully!"
app.py+278-226