Spaces:
Running on Zero
Running on Zero
update
Browse filesFiles changed (5)
817 unmodified lines818819820821822823824825826827828829830817 unmodified lines<a href="https://horizonrobotics.github.io/EmbodiedGen"><img alt="📖 Documentation" src="https://img.shields.io/badge/📖-Documentation-blue"></a><a href="https://arxiv.org/abs/2506.10600"><img alt="📄 arXiv" src="https://img.shields.io/badge/📄-arXiv-b31b1b"></a><a href="https://github.com/HorizonRobotics/EmbodiedGen"><img alt="💻 GitHub" src="https://img.shields.io/badge/GitHub-000000?logo=github"></a><a href="https://www.youtube.com/watch?v=rG4odybuJRk"><img alt="🎥 Video" src="https://img.shields.io/badge/🎥-Video-red"></a></p>817 unmodified lines818819820821822823824825826827828829830817 unmodified lines<a href="https://horizonrobotics.github.io/EmbodiedGen"><img alt="📖 Documentation" src="https://img.shields.io/badge/📖-Documentation-blue"></a><a href="https://arxiv.org/abs/2607.07459"><img alt="📄 arXiv" src="https://img.shields.io/badge/📄-arXiv-b31b1b"></a><a href="https://github.com/HorizonRobotics/EmbodiedGen"><img alt="💻 GitHub" src="https://img.shields.io/badge/GitHub-000000?logo=github"></a><a href="https://youtu.be/MIkJJSVM8L4"><img alt="🎥 Video" src="https://img.shields.io/badge/🎥-Video-red"></a></p>
14 unmodified lines1516171819202114 unmodified lines# permissions and limitations under the License.from gradio.themes import Softfrom gradio.themes.utils.colors import gray, neutral, slate, stone, teal, zinclighting_css = """<style>14 unmodified lines1516171819202114 unmodified lines# permissions and limitations under the License.from gradio.themes import Softfrom gradio.themes.utils.colors import gray, stonelighting_css = """<style>
15 unmodified lines1617181920212223242517 unmodified lines43444546474849505152535429 unmodified lines848586878889905 unmodified lines9697989910010115 unmodified lines11711811912012112212312412512612712812913013119 unmodified lines15115215315415515611 unmodified lines16816917017117217317411 unmodified lines186187188189190191100 unmodified lines29229329429529629716 unmodified lines31431531631731831932032132232332432532632732832933033133233333433533633733833915 unmodified linesimport base64import loggingimport mathimport osfrom io import BytesIOfrom typing import Optionalimport openai17 unmodified lines"GPTclient",]_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))CONFIG_FILE = os.path.join(_CURRENT_DIR, "gpt_config.yaml")DEFAULT_GPT_TIMEOUT = float(os.environ.get("GPT_TIMEOUT", 120))# GPT-5.x counts reasoning tokens against this cap, so it must be high# enough to leave room for both reasoning and the visible reply.GPT5_DEFAULT_MAX_COMPLETION_TOKENS = 8192def combine_images_to_grid(29 unmodified linesclass GPTclient:"""A client to interact with GPT models via OpenAI or Azure API.Supports text and image prompts, connection checking, and configurable parameters.5 unmodified linescheck_connection (bool, optional): Whether to check API connection.verbose (bool, optional): Enable verbose logging.timeout (float, optional): Max seconds for a single GPT request.Example:```sh15 unmodified linesdef __init__(self,endpoint: str,api_key: str,model_name: str = "yfb-gpt-4o",api_version: str = None,check_connection: bool = True,verbose: bool = False,timeout: float = DEFAULT_GPT_TIMEOUT,):if api_version is not None:self.client = AzureOpenAI(azure_endpoint=endpoint,api_key=api_key,19 unmodified lineslogger.info(f"Using GPT model: {self.model_name}.")@staticmethoddef _is_gpt5_model(model_name: str) -> bool:name = (model_name or "").lower()11 unmodified linesdef query(self,text_prompt: str,image_base64: Optional[list[str | Image.Image]] = None,system_role: Optional[str] = None,params: Optional[dict] = None,) -> Optional[str]:11 unmodified linesif system_role is None:system_role = "You are a highly knowledgeable assistant specializing in physics, engineering, and object properties." # noqacontent_user = [{"type": "text",100 unmodified linesConnectionError: If connection fails."""try:probe_kwargs = dict(messages=[{"role": "system", "content": "You are a test system."},16 unmodified lines)with open(CONFIG_FILE, "r") as f:config = yaml.safe_load(f)agent_type = config["agent_type"]agent_config = config.get(agent_type, {})# Prefer environment variables, fallback to YAML configendpoint = os.environ.get("ENDPOINT", agent_config.get("endpoint"))api_key = os.environ.get("API_KEY", agent_config.get("api_key"))api_version = os.environ.get("API_VERSION", agent_config.get("api_version"))model_name = os.environ.get("MODEL_NAME", agent_config.get("model_name"))timeout = DEFAULT_GPT_TIMEOUTGPT_CLIENT = GPTclient(endpoint=endpoint,api_key=api_key,api_version=api_version,model_name=model_name,check_connection=False,timeout=timeout,)15 unmodified lines16171819202122232425262728293017 unmodified lines4849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110229 unmodified lines1321331341351361371385 unmodified lines14414514614714814915015115215 unmodified lines16816917017117217317417517617717817918018118218318418518618718818919019119219319419519 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434511 unmodified lines35735835936036136236336436511 unmodified lines377378379380381382383384385386387388389390391392393394395396397398399100 unmodified lines50050150250350450550650750850951051151251351451551651751851916 unmodified lines53653753853954054154254354454554654754854955055155255355415 unmodified linesimport base64import jsonimport loggingimport mathimport osimport shutilimport subprocessimport tempfilefrom io import BytesIOfrom pathlib import Pathfrom typing import Optionalimport openai17 unmodified lines"GPTclient",]CONFIG_FILE = str(Path(__file__).with_name("gpt_config.yaml"))DEFAULT_GPT_TIMEOUT = float(os.environ.get("GPT_TIMEOUT", 90))# GPT-5.x counts reasoning tokens against this cap, so it must be high# enough to leave room for both reasoning and the visible reply.GPT5_DEFAULT_MAX_COMPLETION_TOKENS = 8192_CODEX_DEFAULT_REASONING_EFFORT = "medium"_CODEX_ENV_KEYS = {"ALL_PROXY","CODEX_HOME","HOME","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","PATH",}def _resolve_agent_settings(config: dict, environ: Optional[dict[str, str]] = None) -> dict:"""Resolve one provider configuration with environment overrides."""environ = os.environ if environ is None else environagent_type = config["agent_type"]agent_config = config.get(agent_type, {})provider_override = environ.get("GPT_PROVIDER")if provider_override is not None:agent_config = {}return {"endpoint": environ.get("ENDPOINT", agent_config.get("endpoint")),"api_key": environ.get("API_KEY", agent_config.get("api_key")),"api_version": environ.get("API_VERSION", agent_config.get("api_version")),"model_name": environ.get("MODEL_NAME", agent_config.get("model_name")),"provider": provider_override or agent_config.get("provider"),}def _codex_subprocess_environment() -> dict[str, str]:"""Return the minimal host environment required by Codex CLI."""return {key: valuefor key, value in os.environ.items()if key.upper() in _CODEX_ENV_KEYS}def combine_images_to_grid(29 unmodified linesclass GPTclient:"""A client to interact with GPT models via API or Codex CLI.Supports text and image prompts, connection checking, and configurable parameters.5 unmodified linescheck_connection (bool, optional): Whether to check API connection.verbose (bool, optional): Enable verbose logging.timeout (float, optional): Max seconds for a single GPT request.provider (str, optional): Backend provider. Use ``codex`` to reuse alocal Codex CLI login; otherwise the existing Azure/OpenAI-compatible API selection is preserved.Example:```sh15 unmodified linesdef __init__(self,endpoint: Optional[str],api_key: Optional[str],model_name: Optional[str] = "yfb-gpt-4o",api_version: Optional[str] = None,check_connection: bool = True,verbose: bool = False,timeout: float = DEFAULT_GPT_TIMEOUT,provider: Optional[str] = None,):self.provider = (provider or ("azure" if api_version else "openai")).lower()self.codex_executable = Noneif self.provider == "codex":self.codex_executable = shutil.which("codex")if self.codex_executable is None:raise RuntimeError("Codex CLI was not found. Install Codex and run ""`codex login` before using the Codex provider.")self.client = Noneelif self.provider == "azure" or api_version is not None:self.client = AzureOpenAI(azure_endpoint=endpoint,api_key=api_key,19 unmodified lineslogger.info(f"Using GPT model: {self.model_name}.")def _materialize_codex_image(self,image: str | Image.Image,target_stem: Path,) -> Path:"""Normalize one Codex image input to a temporary PNG file."""target = target_stem.with_suffix(".png")if isinstance(image, Image.Image):image.convert("RGB").save(target, format="PNG")return targetif not isinstance(image, str):raise TypeError("Codex image input must be a path, base64 string, or PIL Image")if not image.startswith("data:"):source = Path(image).expanduser()try:source_is_file = source.is_file()except OSError:source_is_file = Falseif source_is_file:try:with Image.open(source) as source_image:source_image.convert("RGB").save(target, format="PNG")except OSError as exc:raise ValueError(f"Invalid image file: {image}") from excreturn targetif source.suffix.lower() in self.image_formats:raise FileNotFoundError(f"Image file not found: {image}")encoded = imageelse:header, separator, encoded = image.partition(",")if not separator or ";base64" not in header.lower():raise ValueError("Image data URI must contain base64 data")try:image_data = base64.b64decode(encoded, validate=True)with Image.open(BytesIO(image_data)) as decoded_image:decoded_image.convert("RGB").save(target, format="PNG")except (OSError, ValueError) as exc:raise ValueError("Codex image input is neither an existing image nor valid base64") from excreturn targetdef _query_codex(self,text_prompt: str,image_base64: Optional[str | Image.Image | list[str | Image.Image]],system_role: str,params: Optional[dict],) -> str:"""Run one non-interactive Codex CLI request."""params = params or {}with tempfile.TemporaryDirectory(prefix="embodiedgen-codex-") as tmp:tmp_path = Path(tmp)output_path = tmp_path / "response.txt"image_paths = []images = image_base64 or []if not isinstance(images, list):images = [images]for index, image in enumerate(images):image_paths.append(self._materialize_codex_image(image,tmp_path / f"image_{index}",))prompt = f"{system_role}\n\nUser request:\n{text_prompt}"command = [self.codex_executable,"exec","--ephemeral","--sandbox","read-only","--skip-git-repo-check","--ignore-user-config","--ignore-rules","--color","never","--output-last-message",str(output_path),"--cd",str(tmp_path),]model_name = params.get("model", self.model_name)if model_name:command.extend(["--model", model_name])reasoning_effort = params.get("model_reasoning_effort", _CODEX_DEFAULT_REASONING_EFFORT)if not isinstance(reasoning_effort, str) or not reasoning_effort:raise ValueError("model_reasoning_effort must be a non-empty string")command.extend(["--config",f"model_reasoning_effort={json.dumps(reasoning_effort)}",])for image_path in image_paths:command.extend(["--image", str(image_path)])command.append("-")result = subprocess.run(command,input=prompt,encoding="utf-8",capture_output=True,timeout=self.timeout,check=False,env=_codex_subprocess_environment(),)if result.returncode != 0:raise RuntimeError(result.stderr.strip() or "Codex CLI failed")response = output_path.read_text(encoding="utf-8").strip()if not response:raise RuntimeError("Codex CLI returned an empty response")return response@staticmethoddef _is_gpt5_model(model_name: str) -> bool:name = (model_name or "").lower()11 unmodified linesdef query(self,text_prompt: str,image_base64: Optional[str | Image.Image | list[str | Image.Image]] = None,system_role: Optional[str] = None,params: Optional[dict] = None,) -> Optional[str]:11 unmodified linesif system_role is None:system_role = "You are a highly knowledgeable assistant specializing in physics, engineering, and object properties." # noqaif self.provider == "codex":try:response = self._query_codex(text_prompt=text_prompt,image_base64=image_base64,system_role=system_role,params=params,)except Exception as e:logger.error(f"Error Codex CLI call: {e}")response = Noneif self.verbose:logger.info(f"Prompt: {text_prompt}")logger.info(f"Response: {response}")return responsecontent_user = [{"type": "text",100 unmodified linesConnectionError: If connection fails."""try:if self.provider == "codex":response = self._query_codex(text_prompt="Reply with OK.",image_base64=None,system_role="You are a test system.",params=None,)if not response:raise ConnectionError("Codex CLI returned an empty response")logger.info("Connection check success.")returnprobe_kwargs = dict(messages=[{"role": "system", "content": "You are a test system."},16 unmodified lines)with open(CONFIG_FILE, "r", encoding="utf-8") as f:config = yaml.safe_load(f)settings = _resolve_agent_settings(config)GPT_CLIENT = GPTclient(endpoint=settings["endpoint"],api_key=settings["api_key"],api_version=settings["api_version"],model_name=settings["model_name"],check_connection=False,timeout=DEFAULT_GPT_TIMEOUT,provider=settings["provider"],)
1234512 unmodified lines181920# config.yamlagent_type: "gpt-5.4" # gpt-4o, gpt-5.4 or gemma-4-31bgpt-4o:endpoint: https://xxx.openai.azure.com12 unmodified linesapi_key: sk-or-v1-xxxapi_version: nullmodel_name: google/gemma-4-31b-it:free1234512 unmodified lines18192021222324252627# config.yamlagent_type: "gpt-5.4" # gpt-4o, gpt-5.4 or gemma-4-31b or codexgpt-4o:endpoint: https://xxx.openai.azure.com12 unmodified linesapi_key: sk-or-v1-xxxapi_version: nullmodel_name: google/gemma-4-31b-it:freecodex:provider: codexendpoint: nullapi_key: nullapi_version: nullmodel_name: null
1VERSION = "v2.0.0"1VERSION = "v2.1.0"
app.py+2-2
app_style.py+1-1
embodied_gen/utils/gpt_clients.py+240-25
embodied_gen/utils/gpt_config.yaml+8-1
embodied_gen/utils/tags.py+1-1