openforma 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forma_cli/__init__.py +5 -0
- forma_cli/app.py +1139 -0
- forma_cli/config.py +112 -0
- forma_cli/credentials.py +141 -0
- forma_cli/local.py +562 -0
- forma_cli/metadata_api.py +138 -0
- forma_cli/project_artifacts.py +182 -0
- forma_cli/sdk.py +571 -0
- forma_core/__init__.py +9 -0
- forma_core/__main__.py +4 -0
- forma_core/_version.py +3 -0
- forma_core/agents/__init__.py +50 -0
- forma_core/agents/clarification.py +194 -0
- forma_core/agents/component_reconciliation.py +99 -0
- forma_core/agents/context_gathering.py +115 -0
- forma_core/agents/continuous.py +537 -0
- forma_core/agents/contracts.py +247 -0
- forma_core/agents/firecrawl_mcp.py +484 -0
- forma_core/agents/lattice.py +239 -0
- forma_core/agents/orchestrator.py +3724 -0
- forma_core/agents/pipeline.py +843 -0
- forma_core/agents/project_correction.py +83 -0
- forma_core/agents/prompt_compaction.py +428 -0
- forma_core/agents/system_architecture.py +345 -0
- forma_core/agents/video_correction.py +119 -0
- forma_core/agents/web_research_workflow.py +1256 -0
- forma_core/agents/workflows.py +176 -0
- forma_core/assets/__init__.py +1 -0
- forma_core/assets/models.py +156 -0
- forma_core/assets/project.py +17 -0
- forma_core/assets/repository.py +48 -0
- forma_core/assets/service.py +142 -0
- forma_core/assets/validation.py +35 -0
- forma_core/benchmarks/__init__.py +5 -0
- forma_core/benchmarks/ir_triad_v1.py +477 -0
- forma_core/biology/__init__.py +28 -0
- forma_core/biology/benchmark.py +80 -0
- forma_core/biology/ewart_liverchip.py +279 -0
- forma_core/biology/ir.py +25 -0
- forma_core/biology/liverbench.py +416 -0
- forma_core/biology/liverbench_assay.py +251 -0
- forma_core/biology/liverbench_baselines.py +133 -0
- forma_core/biology/liverbench_independent.py +229 -0
- forma_core/biology/liverchip_demo.py +154 -0
- forma_core/biology/liverchip_evidence.py +149 -0
- forma_core/biology/models.py +247 -0
- forma_core/biology/validation.py +72 -0
- forma_core/cad_migrations/__init__.py +6 -0
- forma_core/cad_migrations/cli.py +101 -0
- forma_core/cad_migrations/emitters.py +227 -0
- forma_core/cad_migrations/models.py +121 -0
- forma_core/cad_migrations/planner.py +68 -0
- forma_core/chemistry/__init__.py +5 -0
- forma_core/chemistry/models.py +215 -0
- forma_core/chemistry/stoichiometry.py +272 -0
- forma_core/chemistry/validation.py +179 -0
- forma_core/cli/__init__.py +1 -0
- forma_core/cli/__main__.py +4 -0
- forma_core/cli/main.py +370 -0
- forma_core/config/__init__.py +28 -0
- forma_core/config/compatibility.py +282 -0
- forma_core/config/contract.py +184 -0
- forma_core/config/environment.py +129 -0
- forma_core/config/parti.py +34 -0
- forma_core/config/runtime.py +303 -0
- forma_core/control/__init__.py +10 -0
- forma_core/control/actions.py +136 -0
- forma_core/control/adapters.py +36 -0
- forma_core/control/cli.py +49 -0
- forma_core/control/client.py +124 -0
- forma_core/control/models.py +168 -0
- forma_core/control/opencode_worker.py +80 -0
- forma_core/control/package.py +318 -0
- forma_core/control/rover_scene/__init__.py +1 -0
- forma_core/control/rover_scene/__main__.py +34 -0
- forma_core/control/rover_scene/assets.py +65 -0
- forma_core/control/rover_scene/fleet.py +214 -0
- forma_core/control/rover_scene/host.py +258 -0
- forma_core/control/rover_scene/kinematics.py +35 -0
- forma_core/control/rover_scene/machine.py +347 -0
- forma_core/control/rover_scene/robot.py +166 -0
- forma_core/control/rover_scene/scene.py +206 -0
- forma_core/control/rover_scene/view.py +80 -0
- forma_core/control/rover_scene/web/index.html +25 -0
- forma_core/control/rover_scene/web/viewer.js +148 -0
- forma_core/control/runtime.py +356 -0
- forma_core/control/so101.py +235 -0
- forma_core/control/tasks.py +287 -0
- forma_core/database.py +2362 -0
- forma_core/debug.py +314 -0
- forma_core/domains/__init__.py +7 -0
- forma_core/domains/agents.py +85 -0
- forma_core/domains/base.py +69 -0
- forma_core/domains/benchmark.py +87 -0
- forma_core/domains/cli.py +48 -0
- forma_core/domains/compatibility.py +234 -0
- forma_core/domains/composition.py +372 -0
- forma_core/domains/diagnostics.py +15 -0
- forma_core/domains/generation.py +479 -0
- forma_core/domains/interaction.py +301 -0
- forma_core/domains/planning.py +140 -0
- forma_core/domains/providers.py +214 -0
- forma_core/domains/registry.py +267 -0
- forma_core/domains/selection.py +75 -0
- forma_core/domains/storage.py +60 -0
- forma_core/domains/tools.py +180 -0
- forma_core/electronics/__init__.py +1 -0
- forma_core/electronics/models.py +84 -0
- forma_core/electronics/primitives.py +43 -0
- forma_core/electronics/rules.py +340 -0
- forma_core/external_sources.py +497 -0
- forma_core/fabricator/__init__.py +33 -0
- forma_core/fabricator/__main__.py +7 -0
- forma_core/fabricator/main.py +578 -0
- forma_core/firmware/__init__.py +60 -0
- forma_core/firmware/drivers.py +140 -0
- forma_core/firmware/examples.py +503 -0
- forma_core/firmware/generate.py +520 -0
- forma_core/firmware/models.py +34 -0
- forma_core/firmware/sil/__init__.py +5 -0
- forma_core/firmware/sil/adapter.py +71 -0
- forma_core/firmware/sil/build.py +49 -0
- forma_core/firmware/sil/native/CMakeLists.txt +9 -0
- forma_core/firmware/sil/native/bridge.cpp +112 -0
- forma_core/firmware/sil/native/controller.cpp +123 -0
- forma_core/firmware/sil/native/controller.h +49 -0
- forma_core/firmware/sil/simulator.py +139 -0
- forma_core/firmware/targets.py +111 -0
- forma_core/firmware/validation.py +130 -0
- forma_core/fluidics/__init__.py +6 -0
- forma_core/fluidics/benchmark.py +217 -0
- forma_core/fluidics/calculations.py +79 -0
- forma_core/fluidics/examples.py +54 -0
- forma_core/fluidics/ir.py +25 -0
- forma_core/fluidics/models.py +132 -0
- forma_core/fluidics/topology.py +47 -0
- forma_core/fluidics/validation.py +134 -0
- forma_core/generation.py +32 -0
- forma_core/geometry_bindings/__init__.py +20 -0
- forma_core/geometry_bindings/cad_adapter.py +80 -0
- forma_core/geometry_bindings/models.py +163 -0
- forma_core/geometry_bindings/resolution.py +340 -0
- forma_core/geometry_bindings/tools.py +125 -0
- forma_core/image_providers.py +3049 -0
- forma_core/images.py +3 -0
- forma_core/integrations/__init__.py +1 -0
- forma_core/integrations/huggingface/__init__.py +29 -0
- forma_core/integrations/huggingface/huggingface_artifacts.py +272 -0
- forma_core/jobs/__init__.py +1 -0
- forma_core/jobs/context.py +277 -0
- forma_core/jobs/continuous.py +719 -0
- forma_core/jobs/metrics.py +124 -0
- forma_core/jobs/migrations.py +161 -0
- forma_core/jobs/persistence.py +28 -0
- forma_core/jobs/repositories.py +422 -0
- forma_core/jobs/schema.py +28 -0
- forma_core/jobs/source_usage.py +230 -0
- forma_core/jobs/store.py +476 -0
- forma_core/llm.py +3 -0
- forma_core/llm_providers.py +2682 -0
- forma_core/logs.py +107 -0
- forma_core/mechanics/__init__.py +1 -0
- forma_core/mechanics/gear_benchmark.py +85 -0
- forma_core/mechanics/mechanism_benchmarks.py +345 -0
- forma_core/mechanics/models.py +72 -0
- forma_core/mechanics/primitives.py +109 -0
- forma_core/mechanics/solid_cad.py +83 -0
- forma_core/observability.py +237 -0
- forma_core/openai_streams.py +780 -0
- forma_core/opencode/__init__.py +25 -0
- forma_core/opencode/architecture.py +82 -0
- forma_core/opencode/capabilities.py +130 -0
- forma_core/opencode/models.py +419 -0
- forma_core/opencode/persistence.py +62 -0
- forma_core/opencode/public_events.py +91 -0
- forma_core/opencode/schema.py +28 -0
- forma_core/opencode/store.py +874 -0
- forma_core/persistence/__init__.py +16 -0
- forma_core/persistence/base.py +38 -0
- forma_core/persistence/images.py +598 -0
- forma_core/persistence/migrations.py +200 -0
- forma_core/persistence/models.py +439 -0
- forma_core/persistence/project_artifacts.py +341 -0
- forma_core/persistence/project_reconciliation.py +1094 -0
- forma_core/persistence/providers/__init__.py +4 -0
- forma_core/persistence/providers/sqlite.py +114 -0
- forma_core/persistence/providers/supabase.py +31 -0
- forma_core/persistence/repositories/__init__.py +9 -0
- forma_core/persistence/repositories/base.py +335 -0
- forma_core/persistence/repositories/sqlite.py +1571 -0
- forma_core/persistence/repositories/supabase.py +1576 -0
- forma_core/persistence/schema.py +176 -0
- forma_core/processes/__init__.py +5 -0
- forma_core/processes/models.py +338 -0
- forma_core/processes/validation.py +141 -0
- forma_core/project_list_cache.py +316 -0
- forma_core/prompt_continuity.py +387 -0
- forma_core/providers/__init__.py +39 -0
- forma_core/providers/base.py +28 -0
- forma_core/providers/models.py +138 -0
- forma_core/providers/openai.py +92 -0
- forma_core/providers/openai_compatible.py +190 -0
- forma_core/providers/registry.py +68 -0
- forma_core/providers/registry_utils.py +46 -0
- forma_core/py.typed +1 -0
- forma_core/runtime.py +3 -0
- forma_core/selectors.py +36 -0
- forma_core/signups/__init__.py +5 -0
- forma_core/signups/models.py +49 -0
- forma_core/terminal/__init__.py +1 -0
- forma_core/terminal/dashboard.py +475 -0
- forma_core/terminal/images.py +156 -0
- forma_core/thermal/__init__.py +5 -0
- forma_core/thermal/models.py +361 -0
- forma_core/thermal/validation.py +175 -0
- forma_core/user_integrations.py +2069 -0
- forma_core/utils.py +291 -0
- forma_core/validation.py +83 -0
- forma_core/vertex_auth.py +92 -0
- forma_core/video_prompts.py +193 -0
- forma_core/video_review.py +1006 -0
- forma_core/wiring.py +356 -0
- forma_core/workers/__init__.py +120 -0
- forma_core/workers/contracts.py +183 -0
- forma_core/workers/generation.py +753 -0
- forma_core/workers/orchestration.py +805 -0
- forma_core/workers/registry.py +222 -0
- forma_core/workers/reverse_engineering.py +272 -0
- forma_core/workers/validation.py +291 -0
- forma_core/workspaces/__init__.py +5 -0
- forma_core/workspaces/chats/__init__.py +11 -0
- forma_core/workspaces/chats/models.py +48 -0
- forma_core/workspaces/context/__init__.py +15 -0
- forma_core/workspaces/context/agent.py +260 -0
- forma_core/workspaces/context/models.py +117 -0
- forma_core/workspaces/context/pdf.py +418 -0
- forma_core/workspaces/design_briefs/__init__.py +25 -0
- forma_core/workspaces/design_briefs/models.py +85 -0
- forma_core/workspaces/design_briefs/references.py +56 -0
- forma_core/workspaces/models.py +41 -0
- forma_core/workspaces/projects/__init__.py +88 -0
- forma_core/workspaces/projects/cad_generation.py +1016 -0
- forma_core/workspaces/projects/context_governance.py +365 -0
- forma_core/workspaces/projects/design_lifecycle.py +668 -0
- forma_core/workspaces/projects/fabrication/__init__.py +54 -0
- forma_core/workspaces/projects/fabrication/demo_printers.py +236 -0
- forma_core/workspaces/projects/fabrication/models.py +120 -0
- forma_core/workspaces/projects/fabrication/printer_config.py +205 -0
- forma_core/workspaces/projects/fabrication/slicers/__init__.py +7 -0
- forma_core/workspaces/projects/fabrication/slicers/base.py +25 -0
- forma_core/workspaces/projects/fabrication/slicers/cura.py +125 -0
- forma_core/workspaces/projects/fabrication/slicers/orca.py +208 -0
- forma_core/workspaces/projects/fabrication/slicing.py +202 -0
- forma_core/workspaces/projects/fabrication/validation.py +103 -0
- forma_core/workspaces/projects/gear_benchmark.py +6 -0
- forma_core/workspaces/projects/generation_mode.py +70 -0
- forma_core/workspaces/projects/identity.py +28 -0
- forma_core/workspaces/projects/iteration.py +680 -0
- forma_core/workspaces/projects/manifest.py +362 -0
- forma_core/workspaces/projects/mechanism_benchmarks.py +12 -0
- forma_core/workspaces/projects/models.py +913 -0
- forma_core/workspaces/projects/objects.py +731 -0
- forma_core/workspaces/projects/outcomes.py +47 -0
- forma_core/workspaces/projects/output.py +735 -0
- forma_core/workspaces/projects/resolver.py +397 -0
- forma_core/workspaces/projects/solid_cad.py +8 -0
- forma_core/workspaces/projects/state.py +622 -0
- forma_core/workspaces/readiness/__init__.py +28 -0
- forma_core/workspaces/readiness/evaluator.py +103 -0
- forma_core/workspaces/readiness/models.py +97 -0
- forma_core/workspaces/readiness/service.py +225 -0
- forma_core/workspaces/reverse_engineering/__init__.py +37 -0
- forma_core/workspaces/reverse_engineering/analyzer.py +246 -0
- forma_core/workspaces/reverse_engineering/models.py +128 -0
- forma_core/workspaces/validation/__init__.py +37 -0
- forma_core/workspaces/validation/evaluator.py +327 -0
- forma_core/workspaces/validation/models.py +146 -0
- forma_core/workspaces/validation/service.py +212 -0
- forma_core/workspaces/workflow/__init__.py +29 -0
- forma_core/workspaces/workflow/guard.py +33 -0
- forma_core/workspaces/workflow/models.py +77 -0
- forma_core/workspaces/workflow/service.py +287 -0
- openforma-0.4.0.dist-info/METADATA +247 -0
- openforma-0.4.0.dist-info/RECORD +288 -0
- openforma-0.4.0.dist-info/WHEEL +5 -0
- openforma-0.4.0.dist-info/entry_points.txt +4 -0
- openforma-0.4.0.dist-info/licenses/LICENSE +373 -0
- openforma-0.4.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import textwrap
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Iterable, Mapping, Sequence
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class DashboardRenderConfig:
|
|
12
|
+
width: int = 1280
|
|
13
|
+
height: int = 900
|
|
14
|
+
background: tuple[int, int, int] = (15, 17, 23)
|
|
15
|
+
scene_yaw_degrees: float = 0.0
|
|
16
|
+
scene_label: str = "LIVE 3D / TERMINAL"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class RenderVector:
|
|
21
|
+
x: float
|
|
22
|
+
y: float
|
|
23
|
+
z: float
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class RenderPlacement:
|
|
28
|
+
ref_des: str
|
|
29
|
+
label: str
|
|
30
|
+
category: str
|
|
31
|
+
layer: str
|
|
32
|
+
position: RenderVector
|
|
33
|
+
size: RenderVector
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class RenderSummary:
|
|
38
|
+
title: str
|
|
39
|
+
description: str
|
|
40
|
+
project_id: str
|
|
41
|
+
provider: str
|
|
42
|
+
model: str
|
|
43
|
+
component_count: int
|
|
44
|
+
net_count: int
|
|
45
|
+
estimated_cost: float
|
|
46
|
+
image_status: str
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
CATEGORY_COLORS: Mapping[str, tuple[int, int, int]] = {
|
|
50
|
+
"microcontroller": (34, 211, 238),
|
|
51
|
+
"sensor": (52, 211, 153),
|
|
52
|
+
"actuator": (251, 146, 60),
|
|
53
|
+
"display": (236, 72, 153),
|
|
54
|
+
"power": (250, 204, 21),
|
|
55
|
+
"passives": (167, 139, 250),
|
|
56
|
+
"communication": (96, 165, 250),
|
|
57
|
+
"mechanical": (251, 113, 133),
|
|
58
|
+
"3d print": (129, 140, 248),
|
|
59
|
+
"default": (148, 163, 184),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _mapping(value: Any) -> Mapping[str, Any]:
|
|
64
|
+
return value if isinstance(value, Mapping) else {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _sequence(value: Any) -> Sequence[Any]:
|
|
68
|
+
return value if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)) else ()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _text(value: Any, default: str = "") -> str:
|
|
72
|
+
return str(value).strip() if value is not None and str(value).strip() else default
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _number(value: Any, default: float = 0.0) -> float:
|
|
76
|
+
try:
|
|
77
|
+
parsed = float(value)
|
|
78
|
+
except (TypeError, ValueError):
|
|
79
|
+
return default
|
|
80
|
+
return parsed if math.isfinite(parsed) else default
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _category_key(value: Any) -> str:
|
|
84
|
+
key = _text(value, "default").lower()
|
|
85
|
+
return key if key in CATEGORY_COLORS else "default"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _vector(value: Any, default: RenderVector) -> RenderVector:
|
|
89
|
+
data = _mapping(value)
|
|
90
|
+
return RenderVector(
|
|
91
|
+
x=_number(data.get("x_mm", data.get("x")), default.x),
|
|
92
|
+
y=_number(data.get("y_mm", data.get("y")), default.y),
|
|
93
|
+
z=_number(data.get("z_mm", data.get("z")), default.z),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _placement_size_for_component(component: Mapping[str, Any]) -> RenderVector:
|
|
98
|
+
name = f"{component.get('name') or ''} {component.get('part_number') or ''}".lower()
|
|
99
|
+
category = _category_key(component.get("category"))
|
|
100
|
+
if "battery" in name:
|
|
101
|
+
return RenderVector(48, 26, 8)
|
|
102
|
+
if "speaker" in name:
|
|
103
|
+
return RenderVector(24, 24, 10)
|
|
104
|
+
if "relay" in name:
|
|
105
|
+
return RenderVector(38, 26, 16)
|
|
106
|
+
if "oled" in name or "display" in name:
|
|
107
|
+
return RenderVector(34, 18, 4)
|
|
108
|
+
if "button" in name or "switch" in name:
|
|
109
|
+
return RenderVector(10, 10, 7)
|
|
110
|
+
defaults = {
|
|
111
|
+
"microcontroller": RenderVector(38, 28, 5),
|
|
112
|
+
"sensor": RenderVector(20, 18, 8),
|
|
113
|
+
"actuator": RenderVector(30, 24, 14),
|
|
114
|
+
"display": RenderVector(32, 18, 4),
|
|
115
|
+
"power": RenderVector(42, 24, 8),
|
|
116
|
+
"mechanical": RenderVector(16, 16, 8),
|
|
117
|
+
"3d print": RenderVector(26, 20, 8),
|
|
118
|
+
}
|
|
119
|
+
return defaults.get(category, RenderVector(22, 18, 6))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _generated_position(index: int, total: int, dimensions: RenderVector) -> RenderVector:
|
|
123
|
+
columns = max(1, math.ceil(math.sqrt(max(total, 1))))
|
|
124
|
+
row = index // columns
|
|
125
|
+
column = index % columns
|
|
126
|
+
x = ((column / max(columns - 1, 1)) - 0.5) * dimensions.x * 0.64
|
|
127
|
+
y = ((row / max(columns - 1, 1)) - 0.5) * dimensions.y * 0.58
|
|
128
|
+
z = -dimensions.z * 0.15 + (index % 3) * min(7, dimensions.z * 0.12)
|
|
129
|
+
return RenderVector(x, y, z)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _placements(project_ir: Mapping[str, Any], dimensions: RenderVector) -> tuple[RenderPlacement, ...]:
|
|
133
|
+
mechanical = _mapping(project_ir.get("mechanical"))
|
|
134
|
+
components = tuple(_mapping(item) for item in _sequence(project_ir.get("components")))
|
|
135
|
+
by_ref = {_text(component.get("ref_des"), f"C{index + 1}"): component for index, component in enumerate(components)}
|
|
136
|
+
placements: list[RenderPlacement] = []
|
|
137
|
+
|
|
138
|
+
for item in _sequence(mechanical.get("component_placements")):
|
|
139
|
+
data = _mapping(item)
|
|
140
|
+
ref = _text(data.get("ref_des") or data.get("ref"))
|
|
141
|
+
if not ref:
|
|
142
|
+
continue
|
|
143
|
+
component = by_ref.get(ref, {})
|
|
144
|
+
label = _text(data.get("label") or component.get("name") or component.get("part_number"), ref)
|
|
145
|
+
category = _text(data.get("category") or component.get("category"), "default")
|
|
146
|
+
placements.append(
|
|
147
|
+
RenderPlacement(
|
|
148
|
+
ref_des=ref,
|
|
149
|
+
label=label,
|
|
150
|
+
category=category,
|
|
151
|
+
layer=_text(data.get("layer"), "electrical"),
|
|
152
|
+
position=_vector(data.get("position_mm") or data.get("position"), RenderVector(0, 0, 0)),
|
|
153
|
+
size=_vector(data.get("size_mm") or data.get("size"), _placement_size_for_component(component)),
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
existing = {placement.ref_des for placement in placements}
|
|
158
|
+
for index, component in enumerate(components):
|
|
159
|
+
ref = _text(component.get("ref_des"), f"C{index + 1}")
|
|
160
|
+
if ref in existing:
|
|
161
|
+
continue
|
|
162
|
+
placements.append(
|
|
163
|
+
RenderPlacement(
|
|
164
|
+
ref_des=ref,
|
|
165
|
+
label=_text(component.get("name") or component.get("part_number"), ref),
|
|
166
|
+
category=_text(component.get("category"), "default"),
|
|
167
|
+
layer="electrical",
|
|
168
|
+
position=_generated_position(index, len(components), dimensions),
|
|
169
|
+
size=_placement_size_for_component(component),
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
return tuple(placements)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _summary(project_ir: Mapping[str, Any], *, subtitle: str = "") -> RenderSummary:
|
|
177
|
+
overview = _mapping(project_ir.get("overview"))
|
|
178
|
+
metadata = _mapping(project_ir.get("assembly_metadata"))
|
|
179
|
+
components = _sequence(project_ir.get("components"))
|
|
180
|
+
nets = _sequence(project_ir.get("nets"))
|
|
181
|
+
image_status = _text(metadata.get("image_output_status") or metadata.get("product_image_status"), "not requested")
|
|
182
|
+
return RenderSummary(
|
|
183
|
+
title=_text(overview.get("title"), "Untitled Hardware Project"),
|
|
184
|
+
description=_text(overview.get("description"), subtitle or "Generated hardware package"),
|
|
185
|
+
project_id=_text(metadata.get("project_id")),
|
|
186
|
+
provider=_text(metadata.get("runtime_provider") or metadata.get("llm_provider") or metadata.get("requested_provider")),
|
|
187
|
+
model=_text(metadata.get("runtime_model") or metadata.get("actual_model") or metadata.get("model_name") or metadata.get("requested_model")),
|
|
188
|
+
component_count=len(components),
|
|
189
|
+
net_count=len(nets),
|
|
190
|
+
estimated_cost=_number(overview.get("estimated_cost"), 0.0),
|
|
191
|
+
image_status=image_status,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _dimensions(project_ir: Mapping[str, Any]) -> RenderVector:
|
|
196
|
+
mechanical = _mapping(project_ir.get("mechanical"))
|
|
197
|
+
metadata = _mapping(project_ir.get("assembly_metadata"))
|
|
198
|
+
visual_spec = _mapping(metadata.get("product_visual_spec"))
|
|
199
|
+
return _vector(
|
|
200
|
+
mechanical.get("render_dimensions")
|
|
201
|
+
or visual_spec.get("external_dimensions_mm")
|
|
202
|
+
or metadata.get("render_dimensions"),
|
|
203
|
+
RenderVector(100, 65, 38),
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _font(size: int, *, bold: bool = False) -> Any:
|
|
208
|
+
from PIL import ImageFont
|
|
209
|
+
|
|
210
|
+
names = [
|
|
211
|
+
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
|
|
212
|
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
213
|
+
]
|
|
214
|
+
for name in names:
|
|
215
|
+
try:
|
|
216
|
+
return ImageFont.truetype(name, size)
|
|
217
|
+
except Exception:
|
|
218
|
+
continue
|
|
219
|
+
return ImageFont.load_default()
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _wrap_text(draw: Any, text: str, *, x: int, y: int, width: int, fill: tuple[int, int, int], font: Any, line_gap: int = 6, max_lines: int = 4) -> int:
|
|
223
|
+
approx_chars = max(12, width // max(8, int(getattr(font, "size", 12) * 0.58)))
|
|
224
|
+
lines: list[str] = []
|
|
225
|
+
for paragraph in text.splitlines() or [text]:
|
|
226
|
+
lines.extend(textwrap.wrap(paragraph, width=approx_chars) or [""])
|
|
227
|
+
for line in lines[:max_lines]:
|
|
228
|
+
draw.text((x, y), line, fill=fill, font=font)
|
|
229
|
+
y += getattr(font, "size", 12) + line_gap
|
|
230
|
+
return y
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _fit_text(draw: Any, text: str, *, max_width: int, font: Any) -> str:
|
|
234
|
+
if draw.textlength(text, font=font) <= max_width:
|
|
235
|
+
return text
|
|
236
|
+
ellipsis = "..."
|
|
237
|
+
candidate = text
|
|
238
|
+
while candidate and draw.textlength(candidate + ellipsis, font=font) > max_width:
|
|
239
|
+
candidate = candidate[:-1]
|
|
240
|
+
return (candidate.rstrip() + ellipsis) if candidate else ellipsis
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _shade(color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
|
|
244
|
+
return tuple(max(0, min(255, int(channel * factor))) for channel in color)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _rotate_xy(point: RenderVector, *, yaw_degrees: float) -> RenderVector:
|
|
248
|
+
if not yaw_degrees:
|
|
249
|
+
return point
|
|
250
|
+
radians = math.radians(yaw_degrees)
|
|
251
|
+
cos_yaw = math.cos(radians)
|
|
252
|
+
sin_yaw = math.sin(radians)
|
|
253
|
+
return RenderVector(
|
|
254
|
+
x=point.x * cos_yaw - point.y * sin_yaw,
|
|
255
|
+
y=point.x * sin_yaw + point.y * cos_yaw,
|
|
256
|
+
z=point.z,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _project(point: RenderVector, *, origin: tuple[float, float], scale: float, yaw_degrees: float = 0.0) -> tuple[float, float]:
|
|
261
|
+
point = _rotate_xy(point, yaw_degrees=yaw_degrees)
|
|
262
|
+
cos30 = 0.8660254038
|
|
263
|
+
sin30 = 0.5
|
|
264
|
+
x = origin[0] + (point.x - point.y) * cos30 * scale
|
|
265
|
+
y = origin[1] + (point.x + point.y) * sin30 * scale - point.z * scale
|
|
266
|
+
return x, y
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _add_vectors(left: RenderVector, right: RenderVector) -> RenderVector:
|
|
270
|
+
return RenderVector(left.x + right.x, left.y + right.y, left.z + right.z)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _draw_iso_box(
|
|
274
|
+
draw: Any,
|
|
275
|
+
*,
|
|
276
|
+
center: RenderVector,
|
|
277
|
+
size: RenderVector,
|
|
278
|
+
origin: tuple[float, float],
|
|
279
|
+
scale: float,
|
|
280
|
+
color: tuple[int, int, int],
|
|
281
|
+
outline: tuple[int, int, int],
|
|
282
|
+
yaw_degrees: float = 0.0,
|
|
283
|
+
) -> None:
|
|
284
|
+
half = RenderVector(size.x / 2, size.y / 2, size.z / 2)
|
|
285
|
+
corners = {
|
|
286
|
+
"lll": _add_vectors(center, RenderVector(-half.x, -half.y, -half.z)),
|
|
287
|
+
"rll": _add_vectors(center, RenderVector(half.x, -half.y, -half.z)),
|
|
288
|
+
"rrl": _add_vectors(center, RenderVector(half.x, half.y, -half.z)),
|
|
289
|
+
"lrl": _add_vectors(center, RenderVector(-half.x, half.y, -half.z)),
|
|
290
|
+
"llh": _add_vectors(center, RenderVector(-half.x, -half.y, half.z)),
|
|
291
|
+
"rlh": _add_vectors(center, RenderVector(half.x, -half.y, half.z)),
|
|
292
|
+
"rrh": _add_vectors(center, RenderVector(half.x, half.y, half.z)),
|
|
293
|
+
"lrh": _add_vectors(center, RenderVector(-half.x, half.y, half.z)),
|
|
294
|
+
}
|
|
295
|
+
projected = {key: _project(value, origin=origin, scale=scale, yaw_degrees=yaw_degrees) for key, value in corners.items()}
|
|
296
|
+
top = [projected["llh"], projected["rlh"], projected["rrh"], projected["lrh"]]
|
|
297
|
+
left = [projected["llh"], projected["lrh"], projected["lrl"], projected["lll"]]
|
|
298
|
+
right = [projected["rlh"], projected["rrh"], projected["rrl"], projected["rll"]]
|
|
299
|
+
front = [projected["lrh"], projected["rrh"], projected["rrl"], projected["lrl"]]
|
|
300
|
+
for polygon, fill in ((left, _shade(color, 0.58)), (right, _shade(color, 0.68)), (front, _shade(color, 0.76)), (top, color)):
|
|
301
|
+
draw.polygon(polygon, fill=fill, outline=outline)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _draw_enclosure(draw: Any, *, dimensions: RenderVector, origin: tuple[float, float], scale: float, yaw_degrees: float = 0.0, label: str = "LIVE 3D / TERMINAL") -> None:
|
|
305
|
+
color = (99, 102, 241)
|
|
306
|
+
outline = (196, 181, 253)
|
|
307
|
+
_draw_iso_box(
|
|
308
|
+
draw,
|
|
309
|
+
center=RenderVector(0, 0, 0),
|
|
310
|
+
size=dimensions,
|
|
311
|
+
origin=origin,
|
|
312
|
+
scale=scale,
|
|
313
|
+
color=(42, 45, 58),
|
|
314
|
+
outline=(72, 77, 95),
|
|
315
|
+
yaw_degrees=yaw_degrees,
|
|
316
|
+
)
|
|
317
|
+
half = RenderVector(dimensions.x / 2, dimensions.y / 2, dimensions.z / 2)
|
|
318
|
+
top_points = [
|
|
319
|
+
_project(RenderVector(-half.x, -half.y, half.z), origin=origin, scale=scale, yaw_degrees=yaw_degrees),
|
|
320
|
+
_project(RenderVector(half.x, -half.y, half.z), origin=origin, scale=scale, yaw_degrees=yaw_degrees),
|
|
321
|
+
_project(RenderVector(half.x, half.y, half.z), origin=origin, scale=scale, yaw_degrees=yaw_degrees),
|
|
322
|
+
_project(RenderVector(-half.x, half.y, half.z), origin=origin, scale=scale, yaw_degrees=yaw_degrees),
|
|
323
|
+
]
|
|
324
|
+
draw.line(top_points + [top_points[0]], fill=outline, width=2)
|
|
325
|
+
draw.text((int(origin[0] - 80), int(origin[1] - dimensions.z * scale - 125)), label, fill=color, font=_font(18, bold=True))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _draw_scene(draw: Any, project_ir: Mapping[str, Any], *, bounds: tuple[int, int, int, int], yaw_degrees: float = 0.0, label: str = "LIVE 3D / TERMINAL") -> None:
|
|
329
|
+
left, top, right, bottom = bounds
|
|
330
|
+
dimensions = _dimensions(project_ir)
|
|
331
|
+
placements = _placements(project_ir, dimensions)
|
|
332
|
+
scene_width = right - left
|
|
333
|
+
scene_height = bottom - top
|
|
334
|
+
scale = min(scene_width / max(dimensions.x + dimensions.y, 1) * 0.62, scene_height / max(dimensions.z + (dimensions.x + dimensions.y) * 0.55, 1) * 0.82)
|
|
335
|
+
scale = max(1.5, min(scale, 6.0))
|
|
336
|
+
origin = (left + scene_width * 0.52, top + scene_height * 0.68)
|
|
337
|
+
|
|
338
|
+
for x in range(left, right, 44):
|
|
339
|
+
draw.line([(x, top), (x, bottom)], fill=(29, 33, 43), width=1)
|
|
340
|
+
for y in range(top, bottom, 44):
|
|
341
|
+
draw.line([(left, y), (right, y)], fill=(29, 33, 43), width=1)
|
|
342
|
+
|
|
343
|
+
_draw_enclosure(draw, dimensions=dimensions, origin=origin, scale=scale, yaw_degrees=yaw_degrees, label=label)
|
|
344
|
+
ordered = sorted(placements, key=lambda placement: placement.position.x + placement.position.y + placement.position.z)
|
|
345
|
+
for placement in ordered:
|
|
346
|
+
category = _category_key(placement.category)
|
|
347
|
+
color = CATEGORY_COLORS.get(category, CATEGORY_COLORS["default"])
|
|
348
|
+
_draw_iso_box(
|
|
349
|
+
draw,
|
|
350
|
+
center=placement.position,
|
|
351
|
+
size=placement.size,
|
|
352
|
+
origin=origin,
|
|
353
|
+
scale=scale,
|
|
354
|
+
color=color,
|
|
355
|
+
outline=(229, 231, 235),
|
|
356
|
+
yaw_degrees=yaw_degrees,
|
|
357
|
+
)
|
|
358
|
+
px, py = _project(_add_vectors(placement.position, RenderVector(0, 0, placement.size.z / 2 + 4)), origin=origin, scale=scale, yaw_degrees=yaw_degrees)
|
|
359
|
+
draw.text((int(px) - 18, int(py) - 18), placement.ref_des[:8], fill=(245, 247, 250), font=_font(13, bold=True))
|
|
360
|
+
|
|
361
|
+
footer = f"{int(dimensions.x)}mm X / {int(dimensions.y)}mm Y / {int(dimensions.z)}mm Z / {len(placements)} placements"
|
|
362
|
+
draw.text((left + 24, bottom - 42), footer.upper(), fill=(148, 163, 184), font=_font(15, bold=True))
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _draw_metric(draw: Any, *, x: int, y: int, width: int, label: str, value: str, color: tuple[int, int, int]) -> None:
|
|
366
|
+
draw.rectangle((x, y, x + width, y + 78), fill=(20, 23, 31), outline=(43, 48, 62))
|
|
367
|
+
draw.text((x + 16, y + 14), label.upper(), fill=(117, 135, 174), font=_font(12, bold=True))
|
|
368
|
+
draw.text((x + 16, y + 38), value[:14], fill=color, font=_font(22, bold=True))
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _draw_components(draw: Any, components: Sequence[Any], *, x: int, y: int, width: int, max_rows: int = 8) -> None:
|
|
372
|
+
draw.text((x, y), "COMPONENTS", fill=(226, 232, 240), font=_font(18, bold=True))
|
|
373
|
+
y += 34
|
|
374
|
+
for item in components[:max_rows]:
|
|
375
|
+
component = _mapping(item)
|
|
376
|
+
category = _category_key(component.get("category"))
|
|
377
|
+
color = CATEGORY_COLORS.get(category, CATEGORY_COLORS["default"])
|
|
378
|
+
ref = _text(component.get("ref_des"), "PART")
|
|
379
|
+
name = _text(component.get("name") or component.get("part_number"), "Unnamed component")
|
|
380
|
+
draw.rectangle((x, y, x + width, y + 40), fill=(19, 22, 30), outline=(38, 43, 55))
|
|
381
|
+
draw.rectangle((x, y, x + 5, y + 40), fill=color)
|
|
382
|
+
draw.text((x + 14, y + 11), ref[:8], fill=(248, 250, 252), font=_font(13, bold=True))
|
|
383
|
+
draw.text((x + 86, y + 11), name[:36], fill=(177, 190, 211), font=_font(13))
|
|
384
|
+
y += 46
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _draw_operations(draw: Any, metadata: Mapping[str, Any], *, x: int, y: int, width: int) -> None:
|
|
388
|
+
draw.text((x, y), "OPERATIONS", fill=(226, 232, 240), font=_font(18, bold=True))
|
|
389
|
+
y += 34
|
|
390
|
+
operations = tuple(_mapping(item) for item in _sequence(metadata.get("operation_statuses")))
|
|
391
|
+
if not operations:
|
|
392
|
+
operations = (
|
|
393
|
+
{"label": "Hardware generation", "status": "succeeded"},
|
|
394
|
+
{"label": "Product image", "status": _text(metadata.get("image_output_status"), "not_requested")},
|
|
395
|
+
)
|
|
396
|
+
for operation in operations[:6]:
|
|
397
|
+
status = _text(operation.get("status"), "unknown")
|
|
398
|
+
if status == "succeeded":
|
|
399
|
+
color = (52, 211, 153)
|
|
400
|
+
elif status == "failed":
|
|
401
|
+
color = (251, 113, 133)
|
|
402
|
+
elif status == "pending":
|
|
403
|
+
color = (250, 204, 21)
|
|
404
|
+
else:
|
|
405
|
+
color = (100, 116, 139)
|
|
406
|
+
draw.rectangle((x, y, x + width, y + 32), fill=(19, 22, 30), outline=(38, 43, 55))
|
|
407
|
+
draw.ellipse((x + 12, y + 10, x + 24, y + 22), fill=color)
|
|
408
|
+
draw.text((x + 36, y + 8), _text(operation.get("label") or operation.get("id"), "operation")[:28], fill=(203, 213, 225), font=_font(12, bold=True))
|
|
409
|
+
draw.text((x + width - 110, y + 8), status.upper()[:13], fill=color, font=_font(12, bold=True))
|
|
410
|
+
y += 38
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def render_dashboard_image(
|
|
414
|
+
project_ir: Mapping[str, Any],
|
|
415
|
+
output_path: Path,
|
|
416
|
+
*,
|
|
417
|
+
subtitle: str = "",
|
|
418
|
+
config: DashboardRenderConfig | None = None,
|
|
419
|
+
) -> Path:
|
|
420
|
+
try:
|
|
421
|
+
from PIL import Image, ImageDraw
|
|
422
|
+
except Exception as exc:
|
|
423
|
+
raise RuntimeError(f"Pillow is required for terminal dashboard rendering: {exc}") from exc
|
|
424
|
+
|
|
425
|
+
cfg = config or DashboardRenderConfig()
|
|
426
|
+
image = Image.new("RGB", (cfg.width, cfg.height), cfg.background)
|
|
427
|
+
draw = ImageDraw.Draw(image)
|
|
428
|
+
summary = _summary(project_ir, subtitle=subtitle)
|
|
429
|
+
metadata = _mapping(project_ir.get("assembly_metadata"))
|
|
430
|
+
components = tuple(_sequence(project_ir.get("components")))
|
|
431
|
+
|
|
432
|
+
draw.rectangle((0, 0, cfg.width, cfg.height), fill=cfg.background)
|
|
433
|
+
draw.rectangle((0, 0, cfg.width, 118), fill=(10, 12, 18))
|
|
434
|
+
title_font = _font(28, bold=True)
|
|
435
|
+
right_header_x = max(620, cfg.width - 430)
|
|
436
|
+
title_width = max(320, right_header_x - 72)
|
|
437
|
+
draw.text((36, 28), _fit_text(draw, summary.title.upper(), max_width=title_width, font=title_font), fill=(248, 250, 252), font=title_font)
|
|
438
|
+
_wrap_text(draw, summary.description, x=38, y=70, width=760, fill=(148, 163, 184), font=_font(14), max_lines=2)
|
|
439
|
+
draw.text((right_header_x, 34), f"PROJECT {summary.project_id or 'unsaved'}"[:44], fill=(34, 211, 238), font=_font(14, bold=True))
|
|
440
|
+
draw.text((right_header_x, 62), f"{summary.provider or 'provider'} / {summary.model or 'model'}"[:44], fill=(226, 232, 240), font=_font(14, bold=True))
|
|
441
|
+
|
|
442
|
+
side_x = int(cfg.width * 0.72)
|
|
443
|
+
side_width = cfg.width - side_x - 36
|
|
444
|
+
metric_y = 142
|
|
445
|
+
metric_gap = 18
|
|
446
|
+
metric_width = max(120, min(180, (side_x - 36 - metric_gap * 3) // 4))
|
|
447
|
+
for index, (label, value, color) in enumerate(
|
|
448
|
+
(
|
|
449
|
+
("Parts", str(summary.component_count), (34, 211, 238)),
|
|
450
|
+
("Nets", str(summary.net_count), (52, 211, 153)),
|
|
451
|
+
("Cost", f"${summary.estimated_cost:.2f}", (250, 204, 21)),
|
|
452
|
+
("Image", summary.image_status[:13].upper(), (167, 139, 250)),
|
|
453
|
+
)
|
|
454
|
+
):
|
|
455
|
+
_draw_metric(draw, x=36 + index * (metric_width + metric_gap), y=metric_y, width=metric_width, label=label, value=value, color=color)
|
|
456
|
+
|
|
457
|
+
scene_bounds = (36, 250, side_x - 24, cfg.height - 34)
|
|
458
|
+
draw.rectangle(scene_bounds, fill=(20, 21, 25), outline=(47, 51, 61), width=2)
|
|
459
|
+
_draw_scene(draw, project_ir, bounds=scene_bounds, yaw_degrees=cfg.scene_yaw_degrees, label=cfg.scene_label)
|
|
460
|
+
|
|
461
|
+
_draw_components(draw, components, x=side_x, y=150, width=side_width)
|
|
462
|
+
_draw_operations(draw, metadata, x=side_x, y=560, width=side_width)
|
|
463
|
+
|
|
464
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
465
|
+
image.save(output_path)
|
|
466
|
+
return output_path
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
__all__ = [
|
|
470
|
+
"DashboardRenderConfig",
|
|
471
|
+
"RenderPlacement",
|
|
472
|
+
"RenderSummary",
|
|
473
|
+
"RenderVector",
|
|
474
|
+
"render_dashboard_image",
|
|
475
|
+
]
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Iterable, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}
|
|
11
|
+
IMAGE_PATH_PATTERN = re.compile(r"((?:~|/|\.{1,2}/)?[A-Za-z0-9_@%+=:,./-]+\.(?:png|jpg|jpeg|webp|gif|bmp))", re.IGNORECASE)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class TerminalImageRenderConfig:
|
|
16
|
+
width: Optional[int] = None
|
|
17
|
+
max_height: int = 40
|
|
18
|
+
background_rgb: tuple[int, int, int] = (0, 0, 0)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TerminalImageRenderer:
|
|
22
|
+
def __init__(self, config: TerminalImageRenderConfig | None = None) -> None:
|
|
23
|
+
self.config = config or TerminalImageRenderConfig()
|
|
24
|
+
|
|
25
|
+
def render(self, path: Path) -> str:
|
|
26
|
+
try:
|
|
27
|
+
from PIL import Image
|
|
28
|
+
except Exception as exc:
|
|
29
|
+
return f"[terminal-image] Pillow is required to render images: {exc}"
|
|
30
|
+
|
|
31
|
+
resolved = path.expanduser()
|
|
32
|
+
if not resolved.exists():
|
|
33
|
+
return f"[terminal-image] missing image: {resolved}"
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
with Image.open(resolved) as opened:
|
|
37
|
+
image = opened.convert("RGBA")
|
|
38
|
+
except Exception as exc:
|
|
39
|
+
return f"[terminal-image] unreadable image={resolved} error={exc}"
|
|
40
|
+
|
|
41
|
+
image = self._composite_alpha(image)
|
|
42
|
+
image = self._resize(image)
|
|
43
|
+
return self._render_half_blocks(image)
|
|
44
|
+
|
|
45
|
+
def _composite_alpha(self, image: Any) -> Any:
|
|
46
|
+
from PIL import Image
|
|
47
|
+
|
|
48
|
+
background = Image.new("RGBA", image.size, (*self.config.background_rgb, 255))
|
|
49
|
+
background.alpha_composite(image)
|
|
50
|
+
return background.convert("RGB")
|
|
51
|
+
|
|
52
|
+
def _resize(self, image: Any) -> Any:
|
|
53
|
+
terminal_width = shutil.get_terminal_size((100, 40)).columns
|
|
54
|
+
target_width = self.config.width or min(80, terminal_width)
|
|
55
|
+
target_width = max(1, min(target_width, terminal_width))
|
|
56
|
+
source_width, source_height = image.size
|
|
57
|
+
if source_width <= 0 or source_height <= 0:
|
|
58
|
+
return image
|
|
59
|
+
|
|
60
|
+
pixel_height_limit = max(1, self.config.max_height * 2)
|
|
61
|
+
scale = min(target_width / source_width, pixel_height_limit / source_height, 1.0)
|
|
62
|
+
resized_width = max(1, int(source_width * scale))
|
|
63
|
+
resized_height = max(1, int(source_height * scale))
|
|
64
|
+
return image.resize((resized_width, resized_height))
|
|
65
|
+
|
|
66
|
+
def _render_half_blocks(self, image: Any) -> str:
|
|
67
|
+
reset = "\033[0m"
|
|
68
|
+
lines: list[str] = []
|
|
69
|
+
width, height = image.size
|
|
70
|
+
for y in range(0, height, 2):
|
|
71
|
+
cells: list[str] = []
|
|
72
|
+
for x in range(width):
|
|
73
|
+
upper = image.getpixel((x, y))
|
|
74
|
+
lower = image.getpixel((x, min(y + 1, height - 1)))
|
|
75
|
+
cells.append(
|
|
76
|
+
f"\033[38;2;{upper[0]};{upper[1]};{upper[2]}m"
|
|
77
|
+
f"\033[48;2;{lower[0]};{lower[1]};{lower[2]}m"
|
|
78
|
+
"▀"
|
|
79
|
+
)
|
|
80
|
+
lines.append("".join(cells) + reset)
|
|
81
|
+
return "\n".join(lines)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_image_path(value: str) -> bool:
|
|
85
|
+
if value.startswith("data:image/"):
|
|
86
|
+
return False
|
|
87
|
+
if value.startswith(("http://", "https://")):
|
|
88
|
+
return False
|
|
89
|
+
if any(character.isspace() for character in value.strip()):
|
|
90
|
+
return False
|
|
91
|
+
return Path(value.split("?", 1)[0]).suffix.lower() in IMAGE_EXTENSIONS
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def candidate_image_strings(value: str) -> tuple[str, ...]:
|
|
95
|
+
stripped = value.strip()
|
|
96
|
+
if is_image_path(stripped):
|
|
97
|
+
return (stripped,)
|
|
98
|
+
without_urls = re.sub(r"https?://\S+", "", value)
|
|
99
|
+
candidates: list[str] = []
|
|
100
|
+
for match in IMAGE_PATH_PATTERN.finditer(without_urls):
|
|
101
|
+
candidate = match.group(1).rstrip(".,;:)]}'\"")
|
|
102
|
+
if is_image_path(candidate):
|
|
103
|
+
candidates.append(candidate)
|
|
104
|
+
return tuple(candidates)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def extract_image_paths(value: Any, *, base_dir: Path | None = None) -> tuple[Path, ...]:
|
|
108
|
+
paths: list[Path] = []
|
|
109
|
+
|
|
110
|
+
def visit(item: Any) -> None:
|
|
111
|
+
if isinstance(item, dict):
|
|
112
|
+
for nested in item.values():
|
|
113
|
+
visit(nested)
|
|
114
|
+
return
|
|
115
|
+
if isinstance(item, list):
|
|
116
|
+
for nested in item:
|
|
117
|
+
visit(nested)
|
|
118
|
+
return
|
|
119
|
+
if not isinstance(item, str):
|
|
120
|
+
return
|
|
121
|
+
for candidate in candidate_image_strings(item):
|
|
122
|
+
path = Path(candidate).expanduser()
|
|
123
|
+
if not path.is_absolute() and base_dir is not None:
|
|
124
|
+
path = base_dir / path
|
|
125
|
+
paths.append(path)
|
|
126
|
+
|
|
127
|
+
visit(value)
|
|
128
|
+
unique: list[Path] = []
|
|
129
|
+
seen: set[str] = set()
|
|
130
|
+
for path in paths:
|
|
131
|
+
key = str(path)
|
|
132
|
+
if key in seen:
|
|
133
|
+
continue
|
|
134
|
+
seen.add(key)
|
|
135
|
+
unique.append(path)
|
|
136
|
+
return tuple(unique)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def render_images(paths: Iterable[Path], config: TerminalImageRenderConfig | None = None) -> str:
|
|
140
|
+
renderer = TerminalImageRenderer(config)
|
|
141
|
+
sections: list[str] = []
|
|
142
|
+
for path in paths:
|
|
143
|
+
sections.append(f"[terminal-image] {path}")
|
|
144
|
+
sections.append(renderer.render(path))
|
|
145
|
+
return "\n".join(sections)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
__all__ = [
|
|
149
|
+
"IMAGE_EXTENSIONS",
|
|
150
|
+
"TerminalImageRenderConfig",
|
|
151
|
+
"TerminalImageRenderer",
|
|
152
|
+
"candidate_image_strings",
|
|
153
|
+
"extract_image_paths",
|
|
154
|
+
"is_image_path",
|
|
155
|
+
"render_images",
|
|
156
|
+
]
|