Spaces:
Running
Running
github-actions[bot] commited on
Commit ·
538f1d3
1
Parent(s): d0ae716
🤖 Deploy atari_env environment - 2025-10-21 02:05:10
Browse filesFiles changed (24)
- Dockerfile+2-26
- src/core/__pycache__/__init__.cpython-311.pycDeleted
- src/core/__pycache__/__init__.cpython-313.pycDeleted
- src/core/__pycache__/http_env_client.cpython-311.pycDeleted
- src/core/__pycache__/types.cpython-311.pycDeleted
- src/core/containers/__pycache__/__init__.cpython-311.pycDeleted
- src/core/containers/runtime/__pycache__/__init__.cpython-311.pycDeleted
- src/core/containers/runtime/__pycache__/providers.cpython-311.pycDeleted
- src/core/env_server/__pycache__/__init__.cpython-311.pycDeleted
- src/core/env_server/__pycache__/__init__.cpython-313.pycDeleted
- src/core/env_server/__pycache__/base_transforms.cpython-311.pycDeleted
- src/core/env_server/__pycache__/base_transforms.cpython-313.pycDeleted
- src/core/env_server/__pycache__/http_server.cpython-311.pycDeleted
- src/core/env_server/__pycache__/http_server.cpython-313.pycDeleted
- src/core/env_server/__pycache__/interfaces.cpython-311.pycDeleted
- src/core/env_server/__pycache__/interfaces.cpython-313.pycDeleted
- src/core/env_server/__pycache__/types.cpython-311.pycDeleted
- src/core/env_server/__pycache__/types.cpython-313.pycDeleted
- src/core/env_server/__pycache__/web_interface.cpython-311.pycDeleted
- src/core/env_server/http_server.py+7-5
- src/core/env_server/types.py+12
- src/core/env_server/web_interface.py+920-71
- src/envs/atari_env/server/Dockerfile+4-1
- src/envs/atari_env/server/app.py+2-2
3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940413 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.# Multi-stage build: First stage builds the base imageFROM python:3.11-slim as base-builder# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \curl \&& rm -rf /var/lib/apt/lists/*# Install Python dependencies that all environments needRUN pip install --no-cache-dir \fastapi>=0.104.0 \"uvicorn[standard]>=0.24.0" \requests>=2.25.0 \wsproto>=1.0.0# Set working directoryWORKDIR /app# Default environment variablesENV PYTHONPATH=/app/srcENV PYTHONUNBUFFERED=1# Second stage: Use the built base image and add environment-specific dependenciesFROM base-builder# Install ALE-specific dependenciesRUN pip install --no-cache-dir \gymnasium>=0.29.0 \ale-py>=0.8.0 \numpy>=1.24.0# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY src/envs/atari_env/ /app/src/envs/atari_env/3 unmodified lines45678910111213141516173 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.# Use the specified openenv-base imageFROM openenv-base:sha-7dd8148# Install ALE-specific dependenciesRUN pip install --no-cache-dir \gymnasium>=0.29.0 \ale-py>=0.8.0 \numpy>=1.24.0# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY src/envs/atari_env/ /app/src/envs/atari_env/
162 unmodified lines1631641651661671681691701711721731741751761771781791801811824 unmodified lines187188189190191192193162 unmodified linesenv: Environment,action_cls: Type[Action],observation_cls: Type[Observation],) -> Any:"""Create a FastAPI application with web interface enabled for Hugging Face deployments.This function checks for the ENABLE_WEB_INTERFACE environment variable to determinewhether to enable the web interface.Args:env: The Environment instance to serveaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsReturns:FastAPI application instance with or without web interface based on environment"""# Check if web interface should be enabled# This can be controlled via environment variable or build argument4 unmodified linesif enable_web:# Import web interface only when neededfrom .web_interface import create_web_interface_appreturn create_web_interface_app(env, action_cls, observation_cls)else:# Use standard FastAPI app without web interfacereturn create_fastapi_app(env, action_cls, observation_cls)162 unmodified lines1631641651661671681691701711721731741751761771781791801811821831844 unmodified lines189190191192193194195162 unmodified linesenv: Environment,action_cls: Type[Action],observation_cls: Type[Observation],env_name: Optional[str] = None,) -> Any:"""Create a FastAPI application with or without web interface.This function creates a FastAPI app with the web interface enabled by default,including README integration for better user experience.Args:env: The Environment instance to serveaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsenv_name: Optional environment name for README loadingReturns:FastAPI application instance with or without web interface and README integration"""# Check if web interface should be enabled# This can be controlled via environment variable or build argument4 unmodified linesif enable_web:# Import web interface only when neededfrom .web_interface import create_web_interface_appreturn create_web_interface_app(env, action_cls, observation_cls, env_name)else:# Use standard FastAPI app without web interfacereturn create_fastapi_app(env, action_cls, observation_cls)
42 unmodified lines43444542 unmodified linesstdout: strstderr: strexit_code: int42 unmodified lines43444546474849505152535455565742 unmodified linesstdout: strstderr: strexit_code: int@dataclassclass EnvironmentMetadata:"""Metadata about an environment for documentation and UI purposes."""name: strdescription: strreadme_content: Optional[str] = Noneversion: Optional[str] = Noneauthor: Optional[str] = Nonedocumentation_url: Optional[str] = None
24 unmodified lines2526272829303125 unmodified lines57585960616263646566101 unmodified lines1681691701711721731742 unmodified lines1771781791801811822 unmodified lines1851861871881891903 unmodified lines19419519619719819920020120220320420520620714 unmodified lines2222232242252262272284 unmodified lines233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263212 unmodified lines4764774784794804815 unmodified lines48748848949049149249349449549649749849950093 unmodified lines5945955965975985996006016026036046 unmodified lines6116126136146156161 unmodified line61861962062162262362457 unmodified lines6826836846856866872 unmodified lines69069169269369469569669769869970070170270314 unmodified lines7187197207217227236 unmodified lines73073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376424 unmodified linesfrom pydantic import BaseModelfrom .interfaces import Environmentfrom .types import Action, Observation, State@dataclass25 unmodified linesenv: Environment,action_cls: Type[Action],observation_cls: Type[Observation],):self.env = envself.action_cls = action_clsself.observation_cls = observation_clsself.episode_state = EpisodeState(episode_id=None,step_count=0,101 unmodified linesdef _deserialize_action(self, action_data: Dict[str, Any]) -> Action:"""Convert JSON dict to Action instance."""metadata = action_data.pop("metadata", {})action = self.action_cls(**action_data)action.metadata = metadatareturn action2 unmodified linesenv: Environment,action_cls: Type[Action],observation_cls: Type[Observation],) -> FastAPI:"""Create a FastAPI application with web interface for the given environment.2 unmodified linesenv: The Environment instance to serveaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsReturns:FastAPI application instance with web interface3 unmodified lines# Create the base environment appapp = create_fastapi_app(env, action_cls, observation_cls)# Create web interface managerweb_manager = WebInterfaceManager(env, action_cls, observation_cls)# Add web interface routes@app.get("/web", response_class=HTMLResponse)async def web_interface():"""Serve the web interface."""return get_web_interface_html(action_cls)@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket):14 unmodified lines@app.post("/web/step")async def web_step(request: Dict[str, Any]):"""Step endpoint for web interface."""action_data = request.get("action", {})return await web_manager.step_environment(action_data)@app.get("/web/state")4 unmodified linesreturn appdef get_web_interface_html(action_cls: Type[Action]) -> str:"""Generate the HTML for the web interface."""# Get action fields for dynamic form generationaction_fields = []if hasattr(action_cls, '__dataclass_fields__'):for field_name, field_info in action_cls.__dataclass_fields__.items():if field_name != 'metadata':field_type = field_info.typeif field_type == str:input_type = "text"elif field_type == int:input_type = "number"elif field_type == float:input_type = "number"elif field_type == bool:input_type = "checkbox"else:input_type = "text"action_fields.append({'name': field_name,'type': input_type,'required': field_info.default is field_info.default_factory})return f"""<!DOCTYPE html>212 unmodified linesmax-height: 200px;overflow-y: auto;}}</style></head><body>5 unmodified linesHumanAgent Interface</div><div class="pane-content"><!-- Action Form --><div class="action-form"><h3>Take Action</h3><form id="action-form">{_generate_action_form_fields(action_fields)}<button type="submit" class="btn" id="step-btn">Step</button></form></div><!-- Control Buttons --><div style="margin-bottom: 20px;">93 unmodified lines}}setupEventListeners() {{// Action form submissiondocument.getElementById('action-form').addEventListener('submit', (e) => {{e.preventDefault();this.submitAction();}});// Reset buttondocument.getElementById('reset-btn').addEventListener('click', () => {{6 unmodified lines}});}}async submitAction() {{const formData = new FormData(document.getElementById('action-form'));const action = {{}};1 unmodified line// Collect form datafor (const [key, value] of formData.entries()) {{if (value !== '') {{action[key] = value;}}}}57 unmodified lines}}updateUI(episodeState) {{// Update current statedocument.getElementById('env-status').textContent =episodeState.is_reset ? 'Reset' : 'Running';2 unmodified linesdocument.getElementById('step-count').textContent =episodeState.step_count.toString();// Update current observationconst observationDiv = document.getElementById('current-observation');if (episodeState.current_observation) {{observationDiv.textContent = JSON.stringify(episodeState.current_observation, null, 2);}} else {{observationDiv.textContent = 'No observation yet';}}// Update action logs14 unmodified lines`).join('');}}}}}}// Initialize the web interface when the page loads6 unmodified lines""".replace('{_generate_action_form_fields(action_fields)}', _generate_action_form_fields(action_fields))def _generate_action_form_fields(action_fields: List[Dict[str, Any]]) -> str:"""Generate HTML form fields for action input."""if not action_fields:return '<p>No action fields available</p>'fields_html = []for field in action_fields:if field['type'] == 'checkbox':fields_html.append(f'''<div class="form-group"><label><input type="checkbox" name="{field['name']}" value="true">{field['name']}</label></div>''')elif field['type'] == 'text' and 'message' in field['name'].lower():fields_html.append(f'''<div class="form-group"><label for="{field['name']}">{field['name']}:</label><textarea name="{field['name']}" id="{field['name']}" rows="3" placeholder="Enter {field['name']}..."></textarea></div>''')else:fields_html.append(f'''<div class="form-group"><label for="{field['name']}">{field['name']}:</label><input type="{field['type']}" name="{field['name']}" id="{field['name']}" placeholder="Enter {field['name']}..." {"required" if field['required'] else ""}></div>''')return '\n'.join(fields_html)24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010125 unmodified lines127128129130131132133134135136137138139140141101 unmodified lines2432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782 unmodified lines2812822832842852862872 unmodified lines2902912922932942952963 unmodified lines30030130230330430530630730830931031131231331431531631731831932032114 unmodified lines3363373383393403413423433443453463473483493504 unmodified lines355356357358359360361362363364365366367368369370371372373212 unmodified lines5865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918925 unmodified lines89889990090190290390490590690790893 unmodified lines10021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310446 unmodified lines10511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111 unmodified line1113111411151116111711181119112011211122112311241125112611271128112957 unmodified lines1187118811891190119111921193119411952 unmodified lines119811991200120112021203120412051206120712081209121012111212121312141215121614 unmodified lines12311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412556 unmodified lines126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161324 unmodified linesfrom pydantic import BaseModelfrom .interfaces import Environmentfrom .types import Action, Observation, State, EnvironmentMetadatadef load_environment_metadata(env: Environment, env_name: Optional[str] = None) -> EnvironmentMetadata:"""Load environment metadata including README content.Args:env: The environment instanceenv_name: Optional environment name for README file lookupReturns:EnvironmentMetadata with loaded information"""# Try to get metadata from environment if it has a method for itif hasattr(env, 'get_metadata'):return env.get_metadata()# Default metadatametadata = EnvironmentMetadata(name=env_name or env.__class__.__name__,description=f"{env.__class__.__name__} environment",version="1.0.0")# Try to load README from file systemreadme_content = _load_readme_from_filesystem(env_name)if readme_content:metadata.readme_content = readme_contentreturn metadatadef _load_readme_from_filesystem(env_name: Optional[str]) -> Optional[str]:"""Load README content from the filesystem.Tries multiple locations:1. Container filesystem: /app/README.md2. Local development: src/envs/{env_name}/README.md3. Environment variable: ENV_README_PATH"""import osfrom pathlib import Path# Try container filesystem firstcontainer_readme = Path("/app/README.md")if container_readme.exists():try:return container_readme.read_text(encoding='utf-8')except Exception:pass# Try environment variable pathcustom_path = os.environ.get("ENV_README_PATH")if custom_path and Path(custom_path).exists():try:return Path(custom_path).read_text(encoding='utf-8')except Exception:pass# Try local development pathif env_name:local_readme = Path(f"src/envs/{env_name}/README.md")if local_readme.exists():try:return local_readme.read_text(encoding='utf-8')except Exception:passreturn None@dataclass25 unmodified linesenv: Environment,action_cls: Type[Action],observation_cls: Type[Observation],metadata: Optional[EnvironmentMetadata] = None,):self.env = envself.action_cls = action_clsself.observation_cls = observation_clsself.metadata = metadata or EnvironmentMetadata(name=env.__class__.__name__,description=f"{env.__class__.__name__} environment")self.episode_state = EpisodeState(episode_id=None,step_count=0,101 unmodified linesdef _deserialize_action(self, action_data: Dict[str, Any]) -> Action:"""Convert JSON dict to Action instance."""metadata = action_data.pop("metadata", {})# Handle tensor fields that come from JSON as listsprocessed_data = {}for key, value in action_data.items():if key == "tokens" and isinstance(value, (list, str)):# Convert list or string to tensorif isinstance(value, str):# If it's a string, try to parse it as a list of numberstry:import jsonvalue = json.loads(value)except:# If parsing fails, treat as empty listvalue = []if isinstance(value, list):import torchprocessed_data[key] = torch.tensor(value, dtype=torch.long)else:processed_data[key] = valueelif key == "action_id" and isinstance(value, str):# Convert action_id from string to inttry:processed_data[key] = int(value)except ValueError:# If conversion fails, keep original valueprocessed_data[key] = valueelse:processed_data[key] = valueaction = self.action_cls(**processed_data)action.metadata = metadatareturn action2 unmodified linesenv: Environment,action_cls: Type[Action],observation_cls: Type[Observation],env_name: Optional[str] = None,) -> FastAPI:"""Create a FastAPI application with web interface for the given environment.2 unmodified linesenv: The Environment instance to serveaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsenv_name: Optional environment name for README loadingReturns:FastAPI application instance with web interface3 unmodified lines# Create the base environment appapp = create_fastapi_app(env, action_cls, observation_cls)# Load environment metadatametadata = load_environment_metadata(env, env_name)# Create web interface managerweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Add web interface routes@app.get("/web", response_class=HTMLResponse)async def web_interface():"""Serve the web interface."""return get_web_interface_html(action_cls, web_manager.metadata)@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""return asdict(web_manager.metadata)@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket):14 unmodified lines@app.post("/web/step")async def web_step(request: Dict[str, Any]):"""Step endpoint for web interface."""# Check if this is a message-based request (chat environment)if "message" in request:message = request["message"]# Convert message to action using the environment's message_to_action methodaction = web_manager.env.message_to_action(message)action_data = {"tokens": action.tokens.tolist()}else:action_data = request.get("action", {})return await web_manager.step_environment(action_data)@app.get("/web/state")4 unmodified linesreturn appdef get_web_interface_html(action_cls: Type[Action], metadata: Optional[EnvironmentMetadata] = None) -> str:"""Generate the HTML for the web interface."""# Check if this is a chat environment by looking for tokens fieldis_chat_env = Falseif hasattr(action_cls, '__dataclass_fields__'):for field_name, field_info in action_cls.__dataclass_fields__.items():if field_name == 'tokens' and hasattr(field_info.type, '__name__') and 'Tensor' in field_info.type.__name__:is_chat_env = Truebreak# Get action fields for dynamic form generation with enhanced metadataaction_fields = _extract_action_fields(action_cls)return f"""<!DOCTYPE html>212 unmodified linesmax-height: 200px;overflow-y: auto;}}/* Chat Interface Styles */.chat-interface {{background: white;border: 1px solid #e0e0e0;border-radius: 8px;padding: 20px;margin-bottom: 20px;}}.chat-messages {{background: #f8f9fa;border: 1px solid #e0e0e0;border-radius: 8px;padding: 15px;margin-bottom: 15px;max-height: 400px;overflow-y: auto;}}.chat-message {{margin-bottom: 15px;padding: 10px;border-radius: 8px;}}.chat-message:last-child {{margin-bottom: 0;}}.chat-message.user {{background: #e3f2fd;margin-left: 20px;}}.chat-message.assistant {{background: #f3e5f5;margin-right: 20px;}}.chat-message.system {{background: #e8f5e8;font-style: italic;}}.message-role {{font-weight: 600;font-size: 12px;color: #666;margin-bottom: 5px;}}.message-content {{font-size: 14px;line-height: 1.4;}}.chat-input-container {{border-top: 1px solid #e0e0e0;padding-top: 15px;}}.role-selector {{margin-bottom: 10px;}}.role-selector label {{font-weight: 500;margin-right: 10px;}}.role-selector select {{padding: 5px 10px;border: 1px solid #ddd;border-radius: 4px;}}.message-input {{display: flex;gap: 10px;align-items: flex-end;}}.message-input textarea {{flex: 1;padding: 10px;border: 1px solid #ddd;border-radius: 4px;resize: vertical;font-family: inherit;}}.message-input textarea:focus {{outline: none;border-color: #007bff;box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);}}/* Instructions Section Styles */.instructions-section {{background: white;border: 1px solid #e0e0e0;border-radius: 8px;padding: 20px;margin-bottom: 20px;}}.instructions-header {{display: flex;justify-content: space-between;align-items: center;margin-bottom: 15px;}}.instructions-title {{font-size: 18px;font-weight: 600;color: #333;margin: 0;}}.instructions-toggle {{background: #f8f9fa;border: 1px solid #dee2e6;border-radius: 4px;padding: 5px 10px;cursor: pointer;font-size: 12px;color: #6c757d;}}.instructions-toggle:hover {{background: #e9ecef;}}.instructions-content {{display: none;max-height: 400px;overflow-y: auto;border-top: 1px solid #e0e0e0;padding-top: 15px;}}.instructions-content.expanded {{display: block;}}.instructions-content h1,.instructions-content h2,.instructions-content h3 {{color: #333;margin-top: 20px;margin-bottom: 10px;}}.instructions-content h1 {{font-size: 24px;border-bottom: 2px solid #007bff;padding-bottom: 10px;}}.instructions-content h2 {{font-size: 20px;}}.instructions-content h3 {{font-size: 16px;}}.instructions-content p {{margin-bottom: 10px;line-height: 1.6;}}.instructions-content code {{background: #f8f9fa;padding: 2px 4px;border-radius: 3px;font-family: monospace;font-size: 14px;}}.instructions-content pre {{background: #f8f9fa;border: 1px solid #e9ecef;border-radius: 4px;padding: 15px;overflow-x: auto;margin: 10px 0;}}.instructions-content pre code {{background: none;padding: 0;}}.instructions-content ul,.instructions-content ol {{margin: 10px 0;padding-left: 20px;}}.instructions-content li {{margin-bottom: 5px;}}.instructions-content table {{border-collapse: collapse;width: 100%;margin: 15px 0;}}.instructions-content th,.instructions-content td {{border: 1px solid #dee2e6;padding: 8px 12px;text-align: left;}}.instructions-content th {{background: #f8f9fa;font-weight: 600;}}/* Enhanced Form Styles */.help-text {{display: block;margin-top: 5px;font-size: 12px;color: #6c757d;font-style: italic;}}.form-group label {{font-weight: 500;color: #333;margin-bottom: 5px;}}.form-group select {{width: 100%;padding: 8px 12px;border: 1px solid #ddd;border-radius: 4px;font-size: 14px;background-color: white;}}.form-group select:focus {{outline: none;border-color: #007bff;box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);}}.form-group textarea {{width: 100%;padding: 8px 12px;border: 1px solid #ddd;border-radius: 4px;font-size: 14px;font-family: inherit;resize: vertical;}}.form-group textarea:focus {{outline: none;border-color: #007bff;box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);}}.form-group input[type="number"] {{width: 100%;padding: 8px 12px;border: 1px solid #ddd;border-radius: 4px;font-size: 14px;}}.form-group input[type="number"]:focus {{outline: none;border-color: #007bff;box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);}}.form-group input[type="text"]:focus {{outline: none;border-color: #007bff;box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);}}.required-indicator {{color: #dc3545;font-weight: bold;}}.form-group .field-description {{font-size: 11px;color: #666;margin-top: 2px;font-style: italic;}}</style></head><body>5 unmodified linesHumanAgent Interface</div><div class="pane-content"><!-- Instructions Section -->{_generate_instructions_section(metadata)}<!-- Action Form or Chat Interface -->{_generate_action_interface(action_fields, is_chat_env)}<!-- Control Buttons --><div style="margin-bottom: 20px;">93 unmodified lines}}setupEventListeners() {{// Instructions toggleconst instructionsToggle = document.getElementById('instructions-toggle');const instructionsContent = document.getElementById('instructions-content');if (instructionsToggle && instructionsContent) {{instructionsToggle.addEventListener('click', () => {{instructionsContent.classList.toggle('expanded');instructionsToggle.textContent = instructionsContent.classList.contains('expanded')? 'Hide Instructions' : 'Show Instructions';}});}}// Check if this is a chat environmentconst isChatEnv = document.getElementById('chat-messages') !== null;if (isChatEnv) {{// Chat environment event listenersdocument.getElementById('send-message-btn').addEventListener('click', () => {{this.sendMessage();}});// Send message on Enter (but allow Shift+Enter for new lines)document.getElementById('message-input').addEventListener('keydown', (e) => {{if (e.key === 'Enter' && !e.shiftKey) {{e.preventDefault();this.sendMessage();}}}});}} else {{// Traditional action form submissionconst actionForm = document.getElementById('action-form');if (actionForm) {{actionForm.addEventListener('submit', (e) => {{e.preventDefault();this.submitAction();}});}}}}// Reset buttondocument.getElementById('reset-btn').addEventListener('click', () => {{6 unmodified lines}});}}async sendMessage() {{const messageInput = document.getElementById('message-input');const roleSelect = document.getElementById('message-role');const message = messageInput.value.trim();const role = roleSelect.value;if (!message) {{return;}}// Add message to chat display immediatelythis.addMessageToChat(role, message);// Clear inputmessageInput.value = '';try {{// Send message to server to convert to action and stepconst response = await fetch('/web/step', {{method: 'POST',headers: {{ 'Content-Type': 'application/json' }},body: JSON.stringify({{message: {{role: role,content: message}}}})}});if (!response.ok) {{throw new Error(`HTTP error! status: ${{response.status}}`);}}const result = await response.json();console.log('Message sent:', result);}} catch (error) {{console.error('Error sending message:', error);alert('Error sending message: ' + error.message);}}}}addMessageToChat(role, content) {{const chatMessages = document.getElementById('chat-messages');const messageDiv = document.createElement('div');messageDiv.className = `chat-message ${{role}}`;messageDiv.innerHTML = `<div class="message-role">${{role.charAt(0).toUpperCase() + role.slice(1)}}</div><div class="message-content">${{content}}</div>`;chatMessages.appendChild(messageDiv);chatMessages.scrollTop = chatMessages.scrollHeight;}}async submitAction() {{const formData = new FormData(document.getElementById('action-form'));const action = {{}};1 unmodified line// Collect form datafor (const [key, value] of formData.entries()) {{if (value !== '') {{// Handle tensor fields (tokens) - convert comma-separated string to arrayif (key === 'tokens') {{try {{action[key] = value.split(',').map(x => parseInt(x.trim())).filter(x => !isNaN(x));}} catch (e) {{console.error('Error parsing tokens:', e);action[key] = [];}}}} else {{action[key] = value;}}}}}}57 unmodified lines}}updateUI(episodeState) {{// Check if this is a chat environmentconst isChatEnv = document.getElementById('chat-messages') !== null;// Update current statedocument.getElementById('env-status').textContent =episodeState.is_reset ? 'Reset' : 'Running';2 unmodified linesdocument.getElementById('step-count').textContent =episodeState.step_count.toString();if (isChatEnv) {{// Update chat interfacethis.updateChatInterface(episodeState);}} else {{// Update traditional observation displayconst observationDiv = document.getElementById('current-observation');if (episodeState.current_observation) {{observationDiv.textContent = JSON.stringify(episodeState.current_observation, null, 2);}} else {{observationDiv.textContent = 'No observation yet';}}}}// Update action logs14 unmodified lines`).join('');}}}}updateChatInterface(episodeState) {{const chatMessages = document.getElementById('chat-messages');if (!chatMessages) return;// Clear existing messages (except system message)const systemMessage = chatMessages.querySelector('.chat-message.system');chatMessages.innerHTML = '';if (systemMessage) {{chatMessages.appendChild(systemMessage);}}// Add messages from current observationif (episodeState.current_observation && episodeState.current_observation.messages) {{episodeState.current_observation.messages.forEach(msg => {{this.addMessageToChat(msg.role, msg.content);}});}}}}}}// Initialize the web interface when the page loads6 unmodified lines""".replace('{_generate_action_form_fields(action_fields)}', _generate_action_form_fields(action_fields))def _generate_instructions_section(metadata: Optional[EnvironmentMetadata]) -> str:"""Generate the instructions section with environment documentation."""if not metadata or not metadata.readme_content:return ''# Convert markdown to HTML (basic conversion)import rehtml_content = _markdown_to_html(metadata.readme_content)return f'''<!-- Instructions Section --><div class="instructions-section"><div class="instructions-header"><h3 class="instructions-title">{metadata.name}</h3><button class="instructions-toggle" id="instructions-toggle">Show Instructions</button></div><div class="instructions-content" id="instructions-content"><div class="instructions-readme">{html_content}</div></div></div>'''def _extract_action_fields(action_cls: Type[Action]) -> List[Dict[str, Any]]:"""Extract enhanced field metadata from Action class for form generation."""import typingfrom typing import get_origin, get_argsaction_fields = []if not hasattr(action_cls, '__dataclass_fields__'):return action_fieldsfor field_name, field_info in action_cls.__dataclass_fields__.items():if field_name == 'metadata':continuefield_type = field_info.typefield_metadata = _extract_field_metadata(field_name, field_info)# Determine input type based on field typeinput_type = _determine_input_type(field_type)# Check if field is requiredis_required = field_info.default is field_info.default_factoryaction_fields.append({'name': field_name,'type': input_type,'required': is_required,'description': field_metadata.get('description', ''),'default_value': field_metadata.get('default_value'),'choices': field_metadata.get('choices', []),'min_value': field_metadata.get('min_value'),'max_value': field_metadata.get('max_value'),'placeholder': field_metadata.get('placeholder', ''),'help_text': field_metadata.get('help_text', ''),})return action_fieldsdef _extract_field_metadata(field_name: str, field_info) -> Dict[str, Any]:"""Extract metadata from dataclass field including docstring and type hints."""import typingfrom typing import get_origin, get_args, Literal, Union, Optionalmetadata = {}# Extract description from field docstring or annotationif hasattr(field_info, 'metadata') and field_info.metadata:# Check for custom metadatafor meta in field_info.metadata:if isinstance(meta, dict):metadata.update(meta)# Extract type informationfield_type = field_info.typeorigin = get_origin(field_type)# Handle Literal types for dropdown choicesif origin is Literal:args = get_args(field_type)metadata['choices'] = list(args)# Handle Optional typesif origin is Union:args = get_args(field_type)if len(args) == 2 and type(None) in args:# This is Optional[SomeType]non_none_type = args[0] if args[1] is type(None) else args[1]metadata['optional'] = True# Recursively check the non-None type for choicesif get_origin(non_none_type) is Literal:metadata['choices'] = list(get_args(non_none_type))else:# Regular Union typemetadata['choices'] = [str(arg) for arg in args if arg is not type(None)]# Handle numeric constraintsif field_type in (int, float):# Check for common constraint patterns in field nameif 'count' in field_name.lower() or 'num' in field_name.lower():metadata['min_value'] = 0if 'id' in field_name.lower():metadata['min_value'] = 0# Generate placeholder textif 'message' in field_name.lower():metadata['placeholder'] = f'Enter {field_name.replace("_", " ")}...'elif 'code' in field_name.lower():metadata['placeholder'] = 'Enter Python code here...'elif 'tokens' in field_name.lower():metadata['placeholder'] = 'Enter comma-separated token IDs (e.g., 1,2,3,4,5)'else:metadata['placeholder'] = f'Enter {field_name.replace("_", " ")}...'# Generate help text based on field name and typeif 'action_id' in field_name.lower():metadata['help_text'] = 'The action ID to execute in the environment'elif 'game_name' in field_name.lower():metadata['help_text'] = 'Name of the game or environment'elif 'tokens' in field_name.lower():metadata['help_text'] = 'Token IDs as a comma-separated list of integers'elif 'code' in field_name.lower():metadata['help_text'] = 'Python code to execute in the environment'elif 'message' in field_name.lower():metadata['help_text'] = 'Text message to send'return metadatadef _determine_input_type(field_type) -> str:"""Determine the appropriate HTML input type for a field type."""import typingfrom typing import get_origin, get_args, Literal, Union# Handle direct typesif field_type == str:return "text"elif field_type == int:return "number"elif field_type == float:return "number"elif field_type == bool:return "checkbox"# Handle complex typesorigin = get_origin(field_type)if origin is Literal:return "select"elif origin is Union:args = get_args(field_type)if len(args) == 2 and type(None) in args:# Optional type - use the non-None typenon_none_type = args[0] if args[1] is type(None) else args[1]return _determine_input_type(non_none_type)elif all(isinstance(arg, str) for arg in args if arg is not type(None)):return "select"else:return "text"elif hasattr(field_type, '__name__') and 'Tensor' in field_type.__name__:return "tensor"else:return "text"def _markdown_to_html(markdown: str) -> str:"""Convert basic markdown to HTML for README display."""import htmlimport re# Escape HTML firsthtml_content = html.escape(markdown)# Convert headershtml_content = re.sub(r'^# (.*?)$', r'<h1>\1</h1>', html_content, flags=re.MULTILINE)html_content = re.sub(r'^## (.*?)$', r'<h2>\1</h2>', html_content, flags=re.MULTILINE)html_content = re.sub(r'^### (.*?)$', r'<h3>\1</h3>', html_content, flags=re.MULTILINE)# Convert code blockshtml_content = re.sub(r'```(.*?)\n(.*?)\n```', r'<pre><code>\2</code></pre>', html_content, flags=re.DOTALL)html_content = re.sub(r'`([^`]+)`', r'<code>\1</code>', html_content)# Convert bold and italichtml_content = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', html_content)html_content = re.sub(r'\*(.*?)\*', r'<em>\1</em>', html_content)# Convert listshtml_content = re.sub(r'^- (.*?)$', r'<li>\1</li>', html_content, flags=re.MULTILINE)html_content = re.sub(r'(<li>.*</li>)', r'<ul>\1</ul>', html_content, flags=re.DOTALL)# Convert line breakshtml_content = html_content.replace('\n', '<br>')return html_contentdef _generate_action_interface(action_fields: List[Dict[str, Any]], is_chat_env: bool) -> str:"""Generate either a chat interface or action form based on environment type."""if is_chat_env:return _generate_chat_interface()else:return _generate_action_form(action_fields)def _generate_chat_interface() -> str:"""Generate a chat-style interface for chat environments."""return '''<!-- Chat Interface --><div class="chat-interface"><h3>Chat Interface</h3><div class="chat-messages" id="chat-messages"><div class="chat-message system"><div class="message-role">System</div><div class="message-content">Chat environment ready. Send a message to start the conversation.</div></div></div><div class="chat-input-container"><div class="role-selector"><label for="message-role">Role:</label><select id="message-role"><option value="user">User</option><option value="assistant">Assistant</option></select></div><div class="message-input"><textarea id="message-input" placeholder="Type your message here..." rows="3"></textarea><button class="btn" id="send-message-btn">Send Message</button></div></div></div>'''def _generate_action_form(action_fields: List[Dict[str, Any]]) -> str:"""Generate a traditional action form for non-chat environments."""return f'''<!-- Action Form --><div class="action-form"><h3>Take Action</h3><form id="action-form">{_generate_action_form_fields(action_fields)}<button type="submit" class="btn" id="step-btn">Step</button></form></div>'''def _generate_action_form_fields(action_fields: List[Dict[str, Any]]) -> str:"""Generate HTML form fields for action input with enhanced metadata."""if not action_fields:return '<p>No action fields available</p>'fields_html = []for field in action_fields:field_html = _generate_single_field(field)fields_html.append(field_html)return '\n'.join(fields_html)def _generate_single_field(field: Dict[str, Any]) -> str:"""Generate HTML for a single form field with enhanced metadata."""field_name = field['name']field_type = field['type']required = field['required']placeholder = field.get('placeholder', '')help_text = field.get('help_text', '')choices = field.get('choices', [])min_value = field.get('min_value')max_value = field.get('max_value')default_value = field.get('default_value')# Build label with required indicatorlabel_text = field_name.replace('_', ' ').title()if required:label_text += ' <span style="color: red;">*</span>'# Build input attributesinput_attrs = []if required:input_attrs.append('required')if placeholder:input_attrs.append(f'placeholder="{placeholder}"')if min_value is not None:input_attrs.append(f'min="{min_value}"')if max_value is not None:input_attrs.append(f'max="{max_value}"')if default_value is not None:input_attrs.append(f'value="{default_value}"')attrs_str = ' '.join(input_attrs)if field_type == 'checkbox':return f'''<div class="form-group"><label><input type="checkbox" name="{field_name}" value="true" {attrs_str}>{label_text}</label>{f'<small class="help-text">{help_text}</small>' if help_text else ''}</div>'''elif field_type == 'select':options_html = []if not required:options_html.append(f'<option value="">-- Select {label_text} --</option>')for choice in choices:selected = 'selected' if str(choice) == str(default_value) else ''options_html.append(f'<option value="{choice}" {selected}>{choice}</option>')return f'''<div class="form-group"><label for="{field_name}">{label_text}:</label><select name="{field_name}" id="{field_name}" {attrs_str}>{''.join(options_html)}</select>{f'<small class="help-text">{help_text}</small>' if help_text else ''}</div>'''elif field_type == 'tensor':return f'''<div class="form-group"><label for="{field_name}">{label_text} (comma-separated integers):</label><input type="text" name="{field_name}" id="{field_name}" {attrs_str}><small class="help-text">{help_text or 'Enter token IDs as comma-separated integers (e.g., 1,2,3,4,5)'}</small></div>'''elif field_type == 'text' and ('message' in field_name.lower() or 'code' in field_name.lower()):return f'''<div class="form-group"><label for="{field_name}">{label_text}:</label><textarea name="{field_name}" id="{field_name}" rows="3" {attrs_str}></textarea>{f'<small class="help-text">{help_text}</small>' if help_text else ''}</div>'''else:return f'''<div class="form-group"><label for="{field_name}">{label_text}:</label><input type="{field_type}" name="{field_name}" id="{field_name}" {attrs_str}>{f'<small class="help-text">{help_text}</small>' if help_text else ''}</div>'''
8 unmodified lines91011121314159 unmodified lines2526272829308 unmodified lines## CI/CD build: docker build --build-arg BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest \# -f src/envs/atari_env/server/Dockerfile -t atari-env:latest .ARG BASE_IMAGE=envtorch-base:latestFROM ${BASE_IMAGE}# Install ALE-specific dependencies9 unmodified lines# Copy Atari environment codeCOPY src/envs/atari_env/ /app/src/envs/atari_env/# Atari-specific environment variables (can be overridden at runtime)ENV ATARI_GAME=pongENV ATARI_OBS_TYPE=rgb8 unmodified lines91011121314159 unmodified lines2526272829303132338 unmodified lines## CI/CD build: docker build --build-arg BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest \# -f src/envs/atari_env/server/Dockerfile -t atari-env:latest .ARG BASE_IMAGE=openenv-base:latestFROM ${BASE_IMAGE}# Install ALE-specific dependencies9 unmodified lines# Copy Atari environment codeCOPY src/envs/atari_env/ /app/src/envs/atari_env/# Copy README for web interface documentationCOPY src/envs/atari_env/README.md /app/README.md# Atari-specific environment variables (can be overridden at runtime)ENV ATARI_GAME=pongENV ATARI_OBS_TYPE=rgb
62 unmodified lines636465666768697062 unmodified linesframeskip=frameskip,)# Create the FastAPI app with routesapp = create_app(env, AtariAction, AtariObservation)if __name__ == "__main__":62 unmodified lines636465666768697062 unmodified linesframeskip=frameskip,)# Create the FastAPI app with web interface and README integrationapp = create_app(env, AtariAction, AtariObservation, env_name="atari_env")if __name__ == "__main__":
Dockerfile+2-26
src/core/__pycache__/__init__.cpython-311.pycDeleted
src/core/__pycache__/__init__.cpython-313.pycDeleted
src/core/__pycache__/http_env_client.cpython-311.pycDeleted
src/core/__pycache__/types.cpython-311.pycDeleted
src/core/containers/__pycache__/__init__.cpython-311.pycDeleted
src/core/containers/runtime/__pycache__/__init__.cpython-311.pycDeleted
src/core/containers/runtime/__pycache__/providers.cpython-311.pycDeleted
src/core/env_server/__pycache__/__init__.cpython-311.pycDeleted
src/core/env_server/__pycache__/__init__.cpython-313.pycDeleted
src/core/env_server/__pycache__/base_transforms.cpython-311.pycDeleted
src/core/env_server/__pycache__/base_transforms.cpython-313.pycDeleted
src/core/env_server/__pycache__/http_server.cpython-311.pycDeleted
src/core/env_server/__pycache__/http_server.cpython-313.pycDeleted
src/core/env_server/__pycache__/interfaces.cpython-311.pycDeleted
src/core/env_server/__pycache__/interfaces.cpython-313.pycDeleted
src/core/env_server/__pycache__/types.cpython-311.pycDeleted
src/core/env_server/__pycache__/types.cpython-313.pycDeleted
src/core/env_server/__pycache__/web_interface.cpython-311.pycDeleted
src/core/env_server/http_server.py+7-5
src/core/env_server/types.py+12
src/core/env_server/web_interface.py+920-71
src/envs/atari_env/server/Dockerfile+4-1
src/envs/atari_env/server/app.py+2-2