Spaces:
Build error
Build error
import subprocess | |
import os | |
import socket | |
from datetime import datetime | |
import gradio as gr | |
# Function to check if a port is in use | |
def is_port_in_use(port): | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: | |
return sock.connect_ex(('localhost', port)) == 0 | |
# Log file path | |
log_file_path = 'log.txt' | |
# Log the startup time | |
with open(log_file_path, 'a') as log_file: | |
log_file.write(f"\n[{datetime.now()}] Script started.\n") | |
# Port number to check | |
port_to_check = 7860 | |
# Check if the port is already in use | |
if is_port_in_use(port_to_check): | |
print("API service already running, enjoy!") | |
with open(log_file_path, 'a') as log_file: | |
log_file.write(f"[{datetime.now()}] API service already running on port {port_to_check}, exiting script.\n") | |
else: | |
# Define the command to run | |
command = ['node', 'api.js'] | |
# Log the startup information | |
with open(log_file_path, 'a') as log_file: | |
log_file.write(f"[{datetime.now()}] No service found on port {port_to_check}. Starting API service...\n") | |
# Open the log file for writing the process output | |
with open(log_file_path, 'a') as log_file: | |
# Spawn the node process if the port is not in use | |
process = subprocess.Popen(command, stdout=log_file, stderr=subprocess.STDOUT, | |
stdin=subprocess.DEVNULL, close_fds=True, | |
start_new_session=True) | |
# Log the process spawn success | |
with open(log_file_path, 'a') as log_file: | |
log_file.write(f"[{datetime.now()}] API service started and running in the background.\n") | |
# Gradio app to display the HTML documentation | |
documentation_html = """ | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>API Documentation</title> | |
<style> | |
body { | |
font-family: Arial, sans-serif; | |
line-height: 1.6; | |
max-width: 800px; | |
margin: 20px auto; | |
padding: 0 20px; | |
color: #333; | |
} | |
h1 { | |
color: #0056b3; | |
} | |
code { | |
background: #f4f4f4; | |
padding: 2px 6px; | |
border-radius: 4px; | |
} | |
pre { | |
background: #f4f4f4; | |
padding: 10px; | |
border-radius: 4px; | |
overflow-x: auto; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>API Documentation</h1> | |
<p>This page documents the available APIs for the Node.js service, detailing endpoints, parameters, and expected responses.</p> | |
<!-- Content omitted for brevity --> | |
</body> | |
</html> | |
""" | |
# Create a Gradio interface that displays the HTML documentation | |
def show_documentation(): | |
return documentation_html | |
doc_app = gr.Blocks() | |
with doc_app: | |
gr.HTML(show_documentation()) | |
# Launch the Gradio app | |
doc_app.launch(server_port=7861, server_name="0.0.0.0") | |