format: ruff format

This commit is contained in:
Daulet Amirkhanov 2025-09-10 14:16:02 +01:00
parent 88ac0fc46c
commit db705f75ab
2 changed files with 124 additions and 114 deletions

View file

@ -34,7 +34,7 @@ def get_frontend_download_info() -> Tuple[str, str]:
version = get_cognee_version() version = get_cognee_version()
# Clean up version string (remove -local suffix for development) # Clean up version string (remove -local suffix for development)
clean_version = version.replace('-local', '') clean_version = version.replace("-local", "")
# Download from specific release tag to ensure version compatibility # Download from specific release tag to ensure version compatibility
download_url = f"https://github.com/topoteretes/cognee/archive/refs/tags/v{clean_version}.zip" download_url = f"https://github.com/topoteretes/cognee/archive/refs/tags/v{clean_version}.zip"
@ -79,12 +79,14 @@ def download_frontend_assets(force: bool = False) -> bool:
archive_path = temp_path / "cognee-main.zip" archive_path = temp_path / "cognee-main.zip"
# Download the actual cognee repository from releases # Download the actual cognee repository from releases
logger.info(f"Downloading cognee v{version.replace('-local', '')} from GitHub releases...") logger.info(
f"Downloading cognee v{version.replace('-local', '')} from GitHub releases..."
)
logger.info(f"URL: {download_url}") logger.info(f"URL: {download_url}")
response = requests.get(download_url, stream=True, timeout=60) response = requests.get(download_url, stream=True, timeout=60)
response.raise_for_status() response.raise_for_status()
with open(archive_path, 'wb') as f: with open(archive_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192): for chunk in response.iter_content(chunk_size=8192):
f.write(chunk) f.write(chunk)
@ -92,7 +94,7 @@ def download_frontend_assets(force: bool = False) -> bool:
if frontend_dir.exists(): if frontend_dir.exists():
shutil.rmtree(frontend_dir) shutil.rmtree(frontend_dir)
with zipfile.ZipFile(archive_path, 'r') as zip_file: with zipfile.ZipFile(archive_path, "r") as zip_file:
# Extract to temp directory first # Extract to temp directory first
extract_dir = temp_path / "extracted" extract_dir = temp_path / "extracted"
zip_file.extractall(extract_dir) zip_file.extractall(extract_dir)
@ -106,7 +108,9 @@ def download_frontend_assets(force: bool = False) -> bool:
break break
if not cognee_frontend_source or not cognee_frontend_source.exists(): if not cognee_frontend_source or not cognee_frontend_source.exists():
logger.error("Could not find cognee-frontend directory in downloaded release archive") logger.error(
"Could not find cognee-frontend directory in downloaded release archive"
)
logger.error("This might indicate a version mismatch or missing release.") logger.error("This might indicate a version mismatch or missing release.")
return False return False
@ -117,13 +121,17 @@ def download_frontend_assets(force: bool = False) -> bool:
# Write version info # Write version info
version_file.write_text(version) version_file.write_text(version)
logger.info(f"✓ Cognee frontend v{version.replace('-local', '')} downloaded and cached successfully!") logger.info(
f"✓ Cognee frontend v{version.replace('-local', '')} downloaded and cached successfully!"
)
return True return True
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
if "404" in str(e): if "404" in str(e):
logger.error(f"Release v{version.replace('-local', '')} not found on GitHub.") logger.error(f"Release v{version.replace('-local', '')} not found on GitHub.")
logger.error("This version might not have been released yet, or you're using a development version.") logger.error(
"This version might not have been released yet, or you're using a development version."
)
logger.error("Try using a stable release version of cognee.") logger.error("Try using a stable release version of cognee.")
else: else:
logger.error(f"Failed to download from GitHub: {str(e)}") logger.error(f"Failed to download from GitHub: {str(e)}")
@ -135,8 +143,6 @@ def download_frontend_assets(force: bool = False) -> bool:
return False return False
def find_frontend_path() -> Optional[Path]: def find_frontend_path() -> Optional[Path]:
""" """
Find the cognee-frontend directory. Find the cognee-frontend directory.
@ -174,8 +180,7 @@ def check_node_npm() -> tuple[bool, str]:
""" """
try: try:
# Check Node.js # Check Node.js
result = subprocess.run(["node", "--version"], result = subprocess.run(["node", "--version"], capture_output=True, text=True, timeout=10)
capture_output=True, text=True, timeout=10)
if result.returncode != 0: if result.returncode != 0:
return False, "Node.js is not installed or not in PATH" return False, "Node.js is not installed or not in PATH"
@ -183,8 +188,7 @@ def check_node_npm() -> tuple[bool, str]:
logger.debug(f"Found Node.js version: {node_version}") logger.debug(f"Found Node.js version: {node_version}")
# Check npm # Check npm
result = subprocess.run(["npm", "--version"], result = subprocess.run(["npm", "--version"], capture_output=True, text=True, timeout=10)
capture_output=True, text=True, timeout=10)
if result.returncode != 0: if result.returncode != 0:
return False, "npm is not installed or not in PATH" return False, "npm is not installed or not in PATH"
@ -219,7 +223,7 @@ def install_frontend_dependencies(frontend_path: Path) -> bool:
cwd=frontend_path, cwd=frontend_path,
capture_output=True, capture_output=True,
text=True, text=True,
timeout=300 # 5 minutes timeout timeout=300, # 5 minutes timeout
) )
if result.returncode == 0: if result.returncode == 0:
@ -247,6 +251,7 @@ def is_development_frontend(frontend_path: Path) -> bool:
try: try:
import json import json
with open(package_json_path) as f: with open(package_json_path) as f:
package_data = json.load(f) package_data = json.load(f)
@ -270,17 +275,10 @@ def start_python_server(frontend_path: Path, host: str, port: int) -> Optional[s
os.chdir(frontend_path) os.chdir(frontend_path)
# Use subprocess to run the server so we can return a process handle # Use subprocess to run the server so we can return a process handle
cmd = [ cmd = ["python", "-m", "http.server", str(port), "--bind", host]
"python", "-m", "http.server", str(port),
"--bind", host
]
process = subprocess.Popen( process = subprocess.Popen(
cmd, cmd, cwd=frontend_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
cwd=frontend_path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
) )
# Restore original directory # Restore original directory
@ -315,9 +313,9 @@ def prompt_user_for_download() -> bool:
Returns True if user consents, False otherwise. Returns True if user consents, False otherwise.
""" """
try: try:
print("\n" + "="*60) print("\n" + "=" * 60)
print("🎨 Cognee UI Setup Required") print("🎨 Cognee UI Setup Required")
print("="*60) print("=" * 60)
print("The cognee frontend is not available on your system.") print("The cognee frontend is not available on your system.")
print("This is required to use the web interface.") print("This is required to use the web interface.")
print("\nWhat will happen:") print("\nWhat will happen:")
@ -328,13 +326,18 @@ def prompt_user_for_download() -> bool:
print("\nThe frontend will then be available offline for future use.") print("\nThe frontend will then be available offline for future use.")
response = input("\nWould you like to download the frontend now? (y/N): ").strip().lower() response = input("\nWould you like to download the frontend now? (y/N): ").strip().lower()
return response in ['y', 'yes'] return response in ["y", "yes"]
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
print("\nOperation cancelled by user.") print("\nOperation cancelled by user.")
return False return False
def start_ui(host: str = "localhost", port: int = 3000, open_browser: bool = True, auto_download: bool = False) -> Optional[subprocess.Popen]: def start_ui(
host: str = "localhost",
port: int = 3000,
open_browser: bool = True,
auto_download: bool = False,
) -> Optional[subprocess.Popen]:
""" """
Start the cognee frontend UI server. Start the cognee frontend UI server.
@ -374,7 +377,9 @@ def start_ui(host: str = "localhost", port: int = 3000, open_browser: bool = Tru
if download_frontend_assets(): if download_frontend_assets():
frontend_path = find_frontend_path() frontend_path = find_frontend_path()
if not frontend_path: if not frontend_path:
logger.error("Download succeeded but frontend still not found. This is unexpected.") logger.error(
"Download succeeded but frontend still not found. This is unexpected."
)
return None return None
else: else:
logger.error("Failed to download frontend assets.") logger.error("Failed to download frontend assets.")
@ -400,8 +405,8 @@ def start_ui(host: str = "localhost", port: int = 3000, open_browser: bool = Tru
# Prepare environment variables # Prepare environment variables
env = os.environ.copy() env = os.environ.copy()
env['HOST'] = host env["HOST"] = host
env['PORT'] = str(port) env["PORT"] = str(port)
# Start the development server # Start the development server
logger.info(f"Starting frontend server at http://{host}:{port}") logger.info(f"Starting frontend server at http://{host}:{port}")
@ -414,7 +419,7 @@ def start_ui(host: str = "localhost", port: int = 3000, open_browser: bool = Tru
env=env, env=env,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True text=True,
) )
# Give it a moment to start up # Give it a moment to start up
@ -430,10 +435,11 @@ def start_ui(host: str = "localhost", port: int = 3000, open_browser: bool = Tru
# Open browser if requested # Open browser if requested
if open_browser: if open_browser:
def open_browser_delayed(): def open_browser_delayed():
time.sleep(5) # Give Next.js time to fully start time.sleep(5) # Give Next.js time to fully start
try: try:
webbrowser.open(f"http://{host}:{port}") # TODO: use dashboard url? webbrowser.open(f"http://{host}:{port}") # TODO: use dashboard url?
except Exception as e: except Exception as e:
logger.warning(f"Could not open browser automatically: {e}") logger.warning(f"Could not open browser automatically: {e}")

View file

@ -13,22 +13,26 @@ import time
async def main(): async def main():
# First, let's add some data to cognee for the UI to display # First, let's add some data to cognee for the UI to display
print("Adding sample data to cognee...") print("Adding sample data to cognee...")
await cognee.add("Natural language processing (NLP) is an interdisciplinary subfield of computer science and information retrieval.") await cognee.add(
await cognee.add("Machine learning (ML) is a subset of artificial intelligence that focuses on algorithms and statistical models.") "Natural language processing (NLP) is an interdisciplinary subfield of computer science and information retrieval."
)
await cognee.add(
"Machine learning (ML) is a subset of artificial intelligence that focuses on algorithms and statistical models."
)
# Generate the knowledge graph # Generate the knowledge graph
print("Generating knowledge graph...") print("Generating knowledge graph...")
await cognee.cognify() await cognee.cognify()
print("\n" + "="*60) print("\n" + "=" * 60)
print("Starting cognee UI...") print("Starting cognee UI...")
print("="*60) print("=" * 60)
# Start the UI server # Start the UI server
server = cognee.start_ui( server = cognee.start_ui(
host="localhost", host="localhost",
port=3000, port=3000,
open_browser=True # This will automatically open your browser open_browser=True, # This will automatically open your browser
) )
if server: if server: