File size: 4,524 Bytes
fbf3c28 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
import os
import subprocess
import json
import time
import re
from pathlib import Path
DB_PATH = "/data/adaptai/migrate/vast/workspace-vast1-2/webui/webui.db"
TOOLS_DIR = Path("/data/adaptai/projects/oui-max/tools")
SCRIPTS_DIR = Path("/data/adaptai/projects/oui-max/scripts")
USER_ID = "11c8250e-3a8c-4320-83f1-5826fd470522" # Hardcoded from previous step
def parse_frontmatter(text: str) -> dict:
# Use a more robust regex that doesn't rely on exact triple quotes
# and handles potential leading/trailing whitespace
m = re.search(r'^\s*"""\s*\n(.*?)\n\s*"""', text, re.DOTALL)
fm = {}
if not m:
return fm
for line in m.group(1).splitlines():
if ':' in line:
k,v = line.split(':',1)
fm[k.strip()] = v.strip()
return fm
def get_function_specs(tool_path: Path) -> list:
# Ensure get_specs.py is executable and uses the correct python
cmd = [
"sudo",
"/venv/main/bin/python3",
str(SCRIPTS_DIR / "get_specs.py"),
str(tool_path)
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=30)
return json.loads(result.stdout)
except subprocess.CalledProcessError as e:
print(f"Error running get_specs.py for {tool_path.stem}: {e.stderr}")
raise
except json.JSONDecodeError:
print(f"Failed to decode JSON from get_specs.py for {tool_path.stem}: {result.stdout}")
raise
def generate_sql_for_tool(tool_path: Path, user_id: str, timestamp: int) -> str:
tool_content = tool_path.read_text()
fm = parse_frontmatter(tool_content)
tool_id = fm.get('id') or tool_path.stem
name = fm.get('title') or tool_path.stem
description = fm.get('description', '')
version = fm.get('version', '')
specs = get_function_specs(tool_path)
specs_json = json.dumps(specs)
meta_json = json.dumps({"description": description, "manifest": {"version": version}})
sql_statements = []
# Tool INSERT (using REPLACE INTO for idempotency in case of re-run)
# Escape single quotes by doubling them for SQL
tool_insert_sql = f"""
REPLACE INTO tool(id,user_id,name,content,specs,meta,created_at,updated_at,valves,access_control) VALUES(
'{tool_id}',
'{user_id}',
'{name.replace("'", "''")}',
'{tool_content.replace("'", "''")}',
'{specs_json.replace("'", "''")}',
'{meta_json.replace("'", "''")}',
{timestamp},
{timestamp},
NULL,
NULL
);
"""
sql_statements.append(tool_insert_sql)
# Function INSERTs (using REPLACE INTO for idempotency)
for spec in specs:
func_name = spec.get('name')
func_id = f"{tool_id}.{func_name}"
func_display_name = f"{name}: {func_name}"
func_description = spec.get('description', '')
func_content_json = json.dumps({"tool": tool_id, "func": func_name})
func_meta_json = json.dumps({"description": func_description, "tool": tool_id})
function_insert_sql = f"""
REPLACE INTO function(id,user_id,name,type,content,meta,created_at,updated_at,valves,is_active,is_global) VALUES(
'{func_id}',
'{user_id}',
'{func_display_name.replace("'", "''")}',
'action',
'{func_content_json.replace("'", "''")}',
'{func_meta_json.replace("'", "''")}',
{timestamp},
{timestamp},
NULL,
1,
1
);
"""
sql_statements.append(function_insert_sql)
return "\n".join(sql_statements)
def main():
timestamp = int(time.time())
for tool_file in sorted(TOOLS_DIR.glob('*.py')):
if tool_file.name.startswith('_'): # Skip _guard.py
continue
print(f"Seeding tool: {tool_file.stem}")
try:
sql_content = generate_sql_for_tool(tool_file, USER_ID, timestamp)
temp_sql_file = SCRIPTS_DIR / f"temp_{tool_file.stem}.sql"
temp_sql_file.write_text(sql_content)
subprocess.run(
["sqlite3", DB_PATH, "-init", str(temp_sql_file)],
check=True,
capture_output=True,
text=True
)
print(f"Successfully seeded {tool_file.stem}")
except subprocess.CalledProcessError as e:
print(f"Error seeding {tool_file.stem}: {e.stderr}")
except Exception as e:
print(f"Unexpected error seeding {tool_file.stem}: {e}")
finally:
if temp_sql_file.exists():
temp_sql_file.unlink() # Delete temp file
if __name__ == '__main__':
main()
|