1use anyhow::{anyhow, Result};
4use std::path::Path;
5
6#[cfg(feature = "comfy-renderer")]
7use crate::backend::ComfyContext;
8#[cfg(feature = "comfy-renderer")]
9use crate::services::comfy::{ValidatedWorkflowTemplate, WorkflowLoader};
10
11#[cfg(feature = "python-renderer")]
12use crate::backend::PythonContext;
13
14use crate::{
15 backend::{self, BuildContext, RuntimeBackend},
16 config::model::AppConfig,
17 RuntimeInput, RuntimeResult, SdxlBackend,
18};
19
20pub fn run_backend(
22 config: &AppConfig,
23 profile_name: &str,
24 input: &RuntimeInput,
25 output_dir: &Path,
26) -> Result<RuntimeResult> {
27 let profile = config
28 .profile(profile_name)
29 .ok_or_else(|| anyhow!("Profile '{}' not found", profile_name))?;
30
31 let backend_def = config
32 .backend(&profile.backend_name)
33 .ok_or_else(|| anyhow!("Backend '{}' not found", profile.backend_name))?;
34
35 if !backend_def.enabled {
36 anyhow::bail!("Backend '{}' is disabled", profile.backend_name);
37 }
38
39 let builder = BuildContext::builder();
40
41 let builder = match &backend_def.options {
42 #[cfg(feature = "comfy-renderer")]
43 crate::config::model::BackendOptions::ComfyUi(cfg) => {
44 let raw = WorkflowLoader::load(&cfg.workflow_template_path)
45 .map_err(|e| anyhow!("Failed to load workflow: {}", e))?;
46 let workflow = ValidatedWorkflowTemplate::new(raw)
47 .map_err(|e| anyhow!("Invalid workflow: {}", e))?;
48
49 let runtime_handle = tokio::runtime::Handle::current();
50 let comfy_ctx = ComfyContext::new(workflow, runtime_handle);
51 builder.with_comfy(comfy_ctx)
52 }
53
54 #[cfg(feature = "python-renderer")]
55 crate::config::model::BackendOptions::Python(cfg) => {
56 let interpreter = cfg.python_path.clone();
57 let script_root = cfg.script_path.parent().map(|p| p.to_path_buf());
58 let environment = None;
59 let python_ctx = PythonContext::new(interpreter, script_root, environment);
60 builder.with_python(python_ctx)
61 }
62
63 _ => builder,
64 };
65
66 let ctx = builder.build();
67 let renderer = backend::build_renderer(backend_def, &ctx)?;
68
69 let backend = SdxlBackend::new(renderer);
71 backend.execute(input, output_dir)
72}