Jibrann commited on
Commit
77768cf
·
verified ·
1 Parent(s): 3ce9074

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. README.md +1 -0
  2. inference.py +171 -41
  3. server/app.py +13 -0
  4. server/app_environment.py +22 -3
  5. server/requirements.txt +2 -1
  6. utils.py +2 -2
README.md CHANGED
@@ -8,5 +8,6 @@ sdk_version: "4.66"
8
  python_version: "3.13"
9
  app_file: server/app.py
10
  pinned: false
 
11
  base_path: /web
12
  ---
 
8
  python_version: "3.13"
9
  app_file: server/app.py
10
  pinned: false
11
+ app_port: 8000
12
  base_path: /web
13
  ---
inference.py CHANGED
@@ -1,41 +1,171 @@
1
- import os
2
- import re
3
- import base64
4
- import textwrap
5
- from io import BytesIO
6
- from typing import List, Optional, Dict
7
-
8
- from openai import OpenAI
9
- import numpy as np
10
- from PIL import Image
11
-
12
-
13
- API_BASE_URL = os.getenv("API_BASE_URL")
14
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
15
- MODEL_NAME = os.getenv("MODEL_NAME")
16
-
17
- SYSTEM_PROMPT = textwrap.dedent(
18
- """
19
- You control a web browser through BrowserGym.
20
- Reply with exactly one action string.
21
- The action must be a valid BrowserGym command such as:
22
- - noop()
23
- - click('<BID>')
24
- - type('selector', 'text to enter')
25
- - fill('selector', 'text to enter')
26
- - send_keys('Enter')
27
- - scroll('down')
28
- Use single quotes around string arguments.
29
- When clicking, use the BrowserGym element IDs (BIDs) listed in the user message.
30
- If you are unsure, respond with noop().
31
- Do not include explanations or additional text.
32
- """
33
- ).strip()
34
-
35
-
36
- def main() -> None:
37
- client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
38
-
39
-
40
- if __name__ == "__main__":
41
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from openai import OpenAI
4
+ import json
5
+ from json import JSONDecodeError
6
+ import time
7
+
8
+ try:
9
+ from models import AppAction, AppObservation
10
+ except ImportError:
11
+ from app.models import AppAction, AppObservation
12
+
13
+ try:
14
+ from server.app_environment import AppEnvironment
15
+ except ImportError:
16
+ from app.server.app_environment import AppEnvironment
17
+
18
+
19
+ load_dotenv()
20
+
21
+ API_URL = os.getenv("API_BASE_URL")
22
+ MODEL = os.getenv("MODEL_NAME")
23
+ API_KEY = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
24
+
25
+ MAX_STEPS = 8
26
+ TEMPERATURE = 0.2
27
+ FALLBACK_ACTION = {
28
+ "isSegmentation": False,
29
+ "placement": {},
30
+ "findObjects": {},
31
+ }
32
+
33
+ DEBUG = True
34
+
35
+ SYSTEM_PROMPT = """
36
+ You are an intelligent agent controlling a 3D object placement environment. Your task is to:
37
+
38
+ 1. **Segment objects** in the environment if `isSegmentation=True`.
39
+ 2. **Identify objects** and their properties (name, stackable) accurately.
40
+ 3. **Place objects** in the 3D grid respecting stacking rules and dimensions.
41
+ 4. **Use rewards and feedback** from previous steps to improve future actions.
42
+
43
+ You must strictly return actions that conform to this Pydantic schema:
44
+
45
+ AppAction:
46
+ {
47
+ placement: Dict[str, Tuple[int, int, int, bool]]
48
+ isSegmentation: bool
49
+ findObjects: Dict[str, Tuple[int, int, int, bool]]
50
+ }
51
+
52
+ Rules:
53
+ - Only report objects that are found or placed; empty dicts are valid if none.
54
+ - Do not modify objects that are already placed unless instructed.
55
+ - Coordinates must be within the grid bounds.
56
+ - Respect stackable property: non-stackable objects cannot be placed on top of another object.
57
+ - Use previous step’s reward and rewardFeedback to adjust your strategy.
58
+
59
+ Output:
60
+ - Always return a valid JSON object conforming to the schema.
61
+ - Do not include any extra text, explanations, or commentary.
62
+ - If no action is possible, return empty dicts for `placement` and `findObjects`.
63
+
64
+ Your goal:
65
+ - Maximize cumulative reward.
66
+ - Identify all objects correctly.
67
+ - Place objects efficiently while respecting stacking rules.
68
+ - Learn from reward feedback to improve placement in future steps.
69
+
70
+ Always return a valid JSON that conforms exactly to the AppAction Pydantic model:
71
+ {"placement": Dict[str, Tuple[int,int,int,bool]] or {}, "isSegmentation": bool, "findObjects": Dict[str, Tuple[int,int,int,bool]] or {}}
72
+
73
+ Actions:
74
+ - To place an object: {"isSegmentation": false, "placement": {"object_name": [x, y, z, stackable]}, "findObjects": {}}
75
+ - To segment objects: {"isSegmentation": true, "placement": {}, "findObjects": {"object_name": [x, y, z, stackable]}}
76
+
77
+ Do not include explanations, text, or extra fields.
78
+ If no objects are found or placed, return empty dicts for placement and findObjects.
79
+ The output must be parseable and valid for AppAction(**json_output).
80
+ """.strip()
81
+
82
+ MESSAGES = [{"role": "system", "content": SYSTEM_PROMPT}]
83
+ HISTORY = []
84
+
85
+
86
+ def _fallback_action() -> AppAction:
87
+ return AppAction(**FALLBACK_ACTION)
88
+
89
+
90
+ def _extract_json_payload(output_str: str) -> str:
91
+ output_str = output_str.strip()
92
+
93
+ if output_str.startswith("```"):
94
+ lines = output_str.splitlines()
95
+ if len(lines) >= 3:
96
+ output_str = "\n".join(lines[1:-1]).strip()
97
+
98
+ start = output_str.find("{")
99
+ end = output_str.rfind("}")
100
+
101
+ if start == -1 or end == -1 or end < start:
102
+ raise JSONDecodeError("No JSON object found in model output", output_str, 0)
103
+
104
+ return output_str[start : end + 1]
105
+
106
+
107
+ def parse_output(output_str: str) -> AppAction:
108
+ try:
109
+ data = json.loads(_extract_json_payload(output_str))
110
+ return AppAction(**data)
111
+ except (JSONDecodeError, TypeError, ValueError) as exc:
112
+ print(f"Invalid Output: {exc}")
113
+ print(f"Raw model output: {output_str!r}")
114
+ return _fallback_action()
115
+
116
+
117
+ def main() -> None:
118
+ if not API_URL or not MODEL or not API_KEY:
119
+ missing = [
120
+ name
121
+ for name, value in (
122
+ ("API_BASE_URL", API_URL),
123
+ ("MODEL_NAME", MODEL),
124
+ ("API_KEY/HF_TOKEN", API_KEY),
125
+ )
126
+ if not value
127
+ ]
128
+ raise RuntimeError(f"Missing required environment variables: {', '.join(missing)}")
129
+
130
+ env = AppEnvironment()
131
+ observation: AppObservation = env.reset()
132
+
133
+ client = OpenAI(
134
+ base_url=API_URL,
135
+ api_key=API_KEY,
136
+ )
137
+ for i in range(1, MAX_STEPS + 1):
138
+ MESSAGES.append(
139
+ {
140
+ "role": "user",
141
+ "content": f"""Observation: {observation.model_dump_json()},
142
+ Previous reward: {observation.reward},
143
+ Previous reward list: {observation.rewardList},
144
+ Previous reward feedback: {observation.rewardFeedback},
145
+ Step: {i}""".strip(),
146
+ }
147
+ )
148
+
149
+ llm_output = client.chat.completions.create(
150
+ model=MODEL,
151
+ messages=MESSAGES,
152
+ temperature=TEMPERATURE,
153
+ )
154
+
155
+ message_content = llm_output.choices[0].message.content or ""
156
+ action: AppAction = parse_output(message_content)
157
+ MESSAGES.append({"role": "assistant", "content": message_content})
158
+ observation: AppObservation = env.step(action)
159
+
160
+ HISTORY.append(observation)
161
+
162
+ if observation.isDone:
163
+ break
164
+
165
+ time.sleep(10000)
166
+
167
+ print(HISTORY)
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
server/app.py CHANGED
@@ -22,6 +22,19 @@ app = create_app(
22
  )
23
 
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def main(host: str = "0.0.0.0", port: int = 8000):
26
  """
27
  Entry point for direct execution via uv run or python -m.
 
22
  )
23
 
24
 
25
+ @app.get("/health")
26
+ def health() -> dict[str, str]:
27
+ return {"status": "ok"}
28
+
29
+
30
+ @app.get("/")
31
+ def root() -> dict[str, str]:
32
+ return {
33
+ "message": "Object Placer API is running",
34
+ "health": "/health",
35
+ }
36
+
37
+
38
  def main(host: str = "0.0.0.0", port: int = 8000):
39
  """
40
  Entry point for direct execution via uv run or python -m.
server/app_environment.py CHANGED
@@ -59,15 +59,34 @@ class AppEnvironment(Environment):
59
  self._state.step_count += 1
60
 
61
  reward = 0.0
62
- if action.isSegmentation:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  reward += 10.0
64
  appendRewardFeedback(self._state, "Segmentation successful.", reward)
65
 
66
- if action.placement:
67
  reward += place(action.isSegmentation, action.placement, self._state)
68
  appendRewardFeedback(self._state, "Object placed successfully.", reward)
69
 
70
- if action.findObjects:
71
  reward += findobject(action.isSegmentation, action.findObjects, self._state)
72
  appendRewardFeedback(self._state, "Object found successfully.", reward)
73
 
 
59
  self._state.step_count += 1
60
 
61
  reward = 0.0
62
+
63
+ if action is None:
64
+ reward -= 10.0
65
+ appendRewardFeedback(
66
+ self._state,
67
+ "No action is of invalid schema or format. Penalty applied.",
68
+ reward,
69
+ )
70
+ return AppObservation(
71
+ currentGrid=self._state.currentGrid,
72
+ positions=self._state.ObjectsPresent,
73
+ objectsLeft=self._state.objectsLeft,
74
+ objectsFound=self._state.objectsFound,
75
+ reward=self._state.reward,
76
+ isDone=self._state.isDone,
77
+ rewardFeedback=self._state.rewardFeedback,
78
+ rewardList=self._state.rewardList,
79
+ )
80
+
81
+ if action.isSegmentation and action is not None:
82
  reward += 10.0
83
  appendRewardFeedback(self._state, "Segmentation successful.", reward)
84
 
85
+ if action.placement and action is not None:
86
  reward += place(action.isSegmentation, action.placement, self._state)
87
  appendRewardFeedback(self._state, "Object placed successfully.", reward)
88
 
89
+ if action.findObjects and action is not None:
90
  reward += findobject(action.isSegmentation, action.findObjects, self._state)
91
  appendRewardFeedback(self._state, "Object found successfully.", reward)
92
 
server/requirements.txt CHANGED
@@ -3,4 +3,5 @@ fastapi
3
  uvicorn
4
  numpy
5
  scikit-learn
6
- matplotlib
 
 
3
  uvicorn
4
  numpy
5
  scikit-learn
6
+ matplotlib
7
+ python-dotenv
utils.py CHANGED
@@ -141,7 +141,7 @@ def place(segment, objects, state):
141
  totalObjs = len(objects)
142
  reward_per_obj_placed = 45.0 / totalObjs
143
 
144
- if segment:
145
  appendRewardFeedback(
146
  state, "Placing objects without segmentation is not allowed.", -60.0
147
  )
@@ -237,7 +237,7 @@ def place(segment, objects, state):
237
 
238
  def findobject(segment, objects, state):
239
 
240
- if not segment:
241
  appendRewardFeedback(
242
  state, "Finding objects without segmentation is not allowed.", -60.0
243
  )
 
141
  totalObjs = len(objects)
142
  reward_per_obj_placed = 45.0 / totalObjs
143
 
144
+ if segment or segment is None:
145
  appendRewardFeedback(
146
  state, "Placing objects without segmentation is not allowed.", -60.0
147
  )
 
237
 
238
  def findobject(segment, objects, state):
239
 
240
+ if not segment or segment is None:
241
  appendRewardFeedback(
242
  state, "Finding objects without segmentation is not allowed.", -60.0
243
  )