This commit is contained in:
root 2025-07-10 19:32:44 +08:00
parent 946673c699
commit 3728bb007b
3 changed files with 95 additions and 17 deletions

View File

@ -54,13 +54,28 @@ class JSONRPCResponse:
self._send_response(notification) self._send_response(notification)
def _send_response(self, response: Dict[str, Any]) -> None: def _send_response(self, response: Dict[str, Any]) -> None:
"""Send JSON-RPC response to stdout""" """Send JSON-RPC response to stdout with proper encoding"""
try: try:
json_str = json.dumps(response, ensure_ascii=False, separators=(',', ':')) # Use ensure_ascii=True to avoid Unicode encoding issues
print(f"JSONRPC:{json_str}") json_str = json.dumps(response, ensure_ascii=True, separators=(',', ':'))
# Ensure stdout is properly configured for UTF-8
output_line = f"JSONRPC:{json_str}"
# Write to stdout with explicit encoding handling
if hasattr(sys.stdout, 'buffer'):
# Python 3: write bytes to buffer to ensure proper encoding
sys.stdout.buffer.write(output_line.encode('utf-8'))
sys.stdout.buffer.write(b'\n')
sys.stdout.buffer.flush()
else:
# Fallback for older Python versions
print(output_line)
sys.stdout.flush() sys.stdout.flush()
except Exception as e: except Exception as e:
# Fallback error response # Fallback error response with safe encoding
try:
fallback = { fallback = {
"jsonrpc": "2.0", "jsonrpc": "2.0",
"id": self.request_id, "id": self.request_id,
@ -70,8 +85,29 @@ class JSONRPCResponse:
"data": str(e) "data": str(e)
} }
} }
print(f"JSONRPC:{json.dumps(fallback)}") fallback_json = json.dumps(fallback, ensure_ascii=True)
fallback_line = f"JSONRPC:{fallback_json}"
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(fallback_line.encode('utf-8'))
sys.stdout.buffer.write(b'\n')
sys.stdout.buffer.flush()
else:
print(fallback_line)
sys.stdout.flush() sys.stdout.flush()
except Exception as fallback_error:
# Last resort: simple error message
error_msg = f"JSONRPC:{{\"jsonrpc\":\"2.0\",\"id\":{self.request_id},\"error\":{{\"code\":-32603,\"message\":\"Encoding error\"}}}}"
try:
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(error_msg.encode('utf-8'))
sys.stdout.buffer.write(b'\n')
sys.stdout.buffer.flush()
else:
print(error_msg)
sys.stdout.flush()
except:
pass # Give up if even this fails
class ProgressReporter: class ProgressReporter:

View File

@ -357,6 +357,24 @@ def main():
"""Command line interface for AI video generation.""" """Command line interface for AI video generation."""
import argparse import argparse
import json import json
import os
# Configure encoding for consistent output
if os.name == 'nt': # Windows
# Set console code page to UTF-8 on Windows
try:
import subprocess
subprocess.run(['chcp', '65001'], shell=True, capture_output=True)
except:
pass
# Ensure stdout uses UTF-8 encoding
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except:
pass
parser = argparse.ArgumentParser(description="AI Video Generator") parser = argparse.ArgumentParser(description="AI Video Generator")
parser.add_argument("--action", required=True, parser.add_argument("--action", required=True,
@ -421,14 +439,29 @@ def main():
request_id="cli_batch_request" request_id="cli_batch_request"
) )
print(json.dumps(result, ensure_ascii=False, indent=2)) # Use safe encoding for final output
result_json = json.dumps(result, ensure_ascii=True, indent=2)
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(result_json.encode('utf-8'))
sys.stdout.buffer.write(b'\n')
sys.stdout.buffer.flush()
else:
print(result_json)
sys.stdout.flush()
except Exception as e: except Exception as e:
error_result = { error_result = {
"status": False, "status": False,
"error": str(e) "error": str(e)
} }
print(json.dumps(error_result, ensure_ascii=False, indent=2)) error_json = json.dumps(error_result, ensure_ascii=True, indent=2)
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(error_json.encode('utf-8'))
sys.stdout.buffer.write(b'\n')
sys.stdout.buffer.flush()
else:
print(error_json)
sys.stdout.flush()
sys.exit(1) sys.exit(1)

View File

@ -59,6 +59,15 @@ async fn execute_python_command(_app: tauri::AppHandle, args: &[String]) -> Resu
cmd.stdout(std::process::Stdio::piped()); cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped());
// Set environment variables for consistent encoding
cmd.env("PYTHONIOENCODING", "utf-8");
cmd.env("PYTHONUNBUFFERED", "1");
// On Windows, ensure UTF-8 console output
if cfg!(target_os = "windows") {
cmd.env("PYTHONUTF8", "1");
}
match cmd.spawn() { match cmd.spawn() {
Ok(process) => { Ok(process) => {
println!("Successfully started Python process with: {}", python_cmd); println!("Successfully started Python process with: {}", python_cmd);