WebashalarForML's picture
Update app.py
5175a91 verified
from flask import Flask, request, jsonify, render_template, send_from_directory, send_file
import cv2, json,base64,io,os,tempfile,logging, re
import numpy as np
from unstructured.partition.pdf import partition_pdf
from PIL import Image
# from imutils.perspective import four_point_transform
from dotenv import load_dotenv
import pytesseract
from werkzeug.utils import secure_filename
from langchain_groq import ChatGroq
from langgraph.prebuilt import create_react_agent
from pdf2image import convert_from_path
from concurrent.futures import ThreadPoolExecutor
from pdf2image.exceptions import PDFInfoNotInstalledError
from typing import Dict, TypedDict, Optional, Any
from langgraph.graph import StateGraph, END
import uuid
import shutil, time
from langchain_experimental.open_clip.open_clip import OpenCLIPEmbeddings
# from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from io import BytesIO
from pathlib import Path
import os
from utils.block_relation_builder import block_builder, variable_adder_main
# ============================== #
# INITIALIZE CLIP EMBEDDER #
# ============================== #
clip_embd = OpenCLIPEmbeddings()
# Configure logging
logging.basicConfig(
level=logging.DEBUG, # Use INFO or ERROR in production
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("/app/logs/app.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
load_dotenv()
# os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
groq_api_key = os.getenv("GROQ_API_KEY")
llm = ChatGroq(
model="meta-llama/llama-4-scout-17b-16e-instruct",
temperature=0,
max_tokens=None,
)
app = Flask(__name__)
# ============================== #
# TESSERACT CONFIGURATION #
# ============================== #
# Set the Tesseract executable path
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
pytesseract.pytesseract.tesseract_cmd = (r'/usr/bin/tesseract')
# Set the TESSDATA_PREFIX environment variable to the directory containing the 'tessdata' folder
# This is crucial for Tesseract to find its language data files (e.g., eng.traineddata)
# os.environ['TESSDATA_PREFIX'] = r'C:\Program Files\Tesseract-OCR'
# poppler_path = r"C:\poppler\Library\bin"
backdrop_images_path = r"app\blocks\Backdrops"
sprite_images_path = r"blocks\sprites"
count = 0
BASE_DIR = Path("/app")
BLOCKS_DIR = BASE_DIR / "blocks"
STATIC_DIR = BASE_DIR / "static"
GEN_PROJECT_DIR = BASE_DIR / "generated_projects"
BACKDROP_DIR = BLOCKS_DIR / "Backdrops"
SPRITE_DIR = BLOCKS_DIR / "sprites"
# === new: outputs rooted under BASE_DIR ===
OUTPUT_DIR = BASE_DIR / "outputs"
DETECTED_IMAGE_DIR = OUTPUT_DIR / "DETECTED_IMAGE"
SCANNED_IMAGE_DIR = OUTPUT_DIR / "SCANNED_IMAGE"
JSON_DIR = OUTPUT_DIR / "EXTRACTED_JSON"
# make all of them in one go
for d in (
BLOCKS_DIR,
STATIC_DIR,
GEN_PROJECT_DIR,
BACKDROP_DIR,
SPRITE_DIR,
OUTPUT_DIR,
DETECTED_IMAGE_DIR,
SCANNED_IMAGE_DIR,
JSON_DIR,
):
d.mkdir(parents=True, exist_ok=True)
# def classify_image_type(description_or_name: str) -> str:
# desc = description_or_name.lower()
# sprite_keywords = ["sprite", "character", "animal", "person", "creature", "robot", "figure"]
# backdrop_keywords = ["background", "scene", "forest", "city", "room", "sky", "mountain", "village"]
# code_block_keywords = [
# "move", "turn", "wait", "repeat", "if", "else", "broadcast",
# "glide", "change", "forever", "when", "switch", "costume",
# "say", "think", "stop", "clone", "touching", "sensing",
# "scratch", "block", "code", "set", "variable"
# ]
# if any(kw in desc for kw in code_block_keywords):
# return "code-block"
# elif any(kw in desc for kw in sprite_keywords):
# return "sprite"
# elif any(kw in desc for kw in backdrop_keywords):
# return "backdrop"
# else:
# return "unknown"
class GameState(TypedDict):
project_json: dict
description: str
project_id: str
project_image: str
pseudo_code: dict
action_plan: Optional[Dict]
temporary_node: Optional[Dict]
# Refined SYSTEM_PROMPT with more explicit Scratch JSON rules, especially for variables
SYSTEM_PROMPT = """
You are an expert AI assistant named GameScratchAgent, specialized in generating and modifying Scratch-VM 3.x game project JSON.
Your core task is to process game descriptions and existing Scratch JSON structures, then produce or update JSON segments accurately.
You possess deep knowledge of Scratch 3.0 project schema, informed by comprehensive reference materials. When generating or modifying the `blocks` section, pay extremely close attention to the following:
**Scratch Project JSON Schema Rules:**
1. **Target Structure (`project.json`'s `targets` array):**
* Each object in the `targets` array represents a Stage or a Sprite.
* `isStage`: A boolean indicating if the target is the Stage (`true`) or a Sprite (`false`).
* `name`: The name of the Stage (e.g., `"Stage"`) or the Sprite (e.g., `"Cat"`). This property replaces `objName` found in older Scratch versions.
* `variables` dictionary: This dictionary maps unique variable IDs to arrays `[variable_name, initial_value, isCloudVariable?]`.
* `variable_name`: The user-defined name of the variable.
* `initial_value`: The variable's initial value, which can be a number or a string.
* `isCloudVariable?`: (Optional) A boolean indicating if it's a cloud variable (`true`) or a local variable (`false` or absent for regular variables).
* Example: `"myVarId123": ["score", 0]`, `"cloudVarId456": ["☁ High Score", "54", true]`
* `lists` dictionary: This dictionary maps unique list IDs to arrays `[list_name, [item1, item2, ...]]`.
* Example: `"myListId789": ["my list", ["apple", "banana"]]`
* `broadcasts` dictionary: This dictionary maps unique broadcast IDs to their names.
* Example: `"myBroadcastId": "Game Over"`
* `blocks` dictionary: This dictionary contains all the blocks belonging to this target. Keys are block IDs, values are block objects.
2. **Block Structure (within a `target`'s `blocks` dictionary):**
* Every block object must have the following core properties:
* [cite_start]`opcode`: A unique internal identifier for the block's specific functionality (e.g., `"motion_movesteps"`, `"event_whenflagclicked"`)[cite: 31, 18, 439, 452].
* `parent`: The ID of the block directly above it in the script stack (or `null` for a top-level block).
* `next`: The ID of the block directly below it in the script stack (or `null` for the end of a stack).
* `inputs`: An object defining values or blocks plugged into the block's input slots. Values are **arrays**.
* `fields`: An object defining dropdown menu selections or direct internal values within the block. Values are **arrays**.
* `shadow`: `true` if it's a shadow block (e.g., a default number input that can be replaced by another block), `false` otherwise.
* `topLevel`: `true` if it's a hat block or a standalone block (not connected to a parent), `false` otherwise.
3. **`inputs` Property Details (for blocks plugged into input slots):**
* **Direct Block Connection (Reporter/Boolean block plugged in):**
* Format: `"<INPUT_NAME>": [1, "<blockId_of_plugged_block>"]`
* Example: `"CONDITION": [1, "someBooleanBlockId"]` (e.g., for an `if` block).
* **Literal Value Input (Shadow block with a literal):**
* Format: `"<INPUT_NAME>": [1, [<type_code>, "<value_string>"]]`
* `type_code`: A numeric code representing the data type. Common codes include: `4` for number, `7` for string/text, `10` for string/message.
* `value_string`: The literal value as a string.
* Examples:
* Number: `"STEPS": [1, [4, "10"]]` (for `move 10 steps` block).
* String/Text: `"MESSAGE": [1, [7, "Hello"]]` (for `say Hello` block).
* String/Message (common for text inputs): `"MESSAGE": [1, [10, "Hello!"]]` (for `say Hello! for 2 secs`).
* **C-Block Substack (blocks within a loop or conditional):**
* Format: `"<SUBSTACK_NAME>": [2, "<blockId_of_first_block_in_substack>"]`
* Common `SUBSTACK_NAME` values are `SUBSTACK` (for `if`, `forever`, `repeat`) and `SUBSTACK2` (for `else` in `if else`).
* Example: `"SUBSTACK": [2, "firstBlockInLoopId"]`
4. **`fields` Property Details (for dropdowns or direct internal values):**
* Used for dropdown menus, variable names, list names, or other static selections directly within the block.
* Format: `"<FIELD_NAME>": ["<selected_value>", null]`
* Examples:
* Dropdown: `"KEY_OPTION": ["space", null]` (for `when space key pressed`).
* Variable Name: `"VARIABLE": ["score", null]` (for `set score to 0`).
* Direction (specific motion block): `"FORWARD_BACKWARD": ["forward", null]` (for `go forward layers`).
5. **Unique IDs:**
* All block IDs, variable IDs, and list IDs must be unique strings (e.g., "myBlock123", "myVarId456", "myListId789"). Do NOT use placeholder strings like "block_id_here".
6. **No Nested `blocks` Dictionary:**
* The `blocks` dictionary should only appear once per `target` (sprite/stage). Do NOT nest a `blocks` dictionary inside an individual block definition. Blocks that are part of a substack are linked via the `SUBSTACK` input.
7. **Asset Properties (for Costumes/Sounds):**
* `assetId`, `md5ext`, `bitmapResolution`, `rotationCenterX`/`rotationCenterY` should be correctly associated with costume and sound objects within the `costumes` and `sounds` arrays.
**General Principles and Important Considerations:**
* **Backward Compatibility:** Adhere strictly to existing Scratch 3.0 opcodes and schema to ensure backward compatibility with older projects. [cite_start]Opcodes must remain consistent to prevent previously saved projects from failing to load or behaving unexpectedly[cite: 18, 19, 25, 65].
* **Forgiving Inputs:** Recognize that Scratch is designed to be "forgiving in its interpretation of inputs." [cite_start]The Scratch VM handles potentially "invalid" inputs gracefully (e.g., converting a number to a string if expected, returning default values like zero or empty strings, or performing no action) rather than crashing[cite: 20, 21, 22, 38, 39, 41]. This implies that precise type matching for inputs might be handled internally by Scratch, allowing for some flexibility in how values are provided, but the agent should aim for the most common and logical type.
"""
SYSTEM_PROMPT_JSON_CORRECTOR ="""
You are an assistant that outputs JSON responses strictly following the given schema.
If the JSON you produce has any formatting errors, missing required fields, or invalid structure, you must identify the problems and correct them.
Always return only valid JSON that fully conforms to the schema below, enclosed in triple backticks (```), without any extra text or explanation.
If you receive an invalid or incomplete JSON response, fix it by:
- Adding any missing required fields with appropriate values.
- Correcting syntax errors such as missing commas, brackets, or quotes.
- Ensuring the JSON structure matches the schema exactly.
Remember: Your output must be valid JSON only, ready to be parsed without errors.
"""
# debugger and resolver agent for Scratch 3.0
# Main agent of the system agent for Scratch 3.0
agent = create_react_agent(
model=llm,
tools=[], # No specific tools are defined here, but could be added later
prompt=SYSTEM_PROMPT
)
agent_json_resolver = create_react_agent(
model=llm,
tools=[], # No specific tools are defined here, but could be added later
prompt=SYSTEM_PROMPT_JSON_CORRECTOR
)
# Helper function to load the block catalog from a JSON file
# def _load_block_catalog(file_path: str) -> Dict:
# """Loads the Scratch block catalog from a specified JSON file."""
# try:
# with open(file_path, 'r') as f:
# catalog = json.load(f)
# logger.info(f"Successfully loaded block catalog from {file_path}")
# return catalog
# except FileNotFoundError:
# logger.error(f"Error: Block catalog file not found at {file_path}")
# # Return an empty dict or raise an error, depending on desired behavior
# return {}
# except json.JSONDecodeError as e:
# logger.error(f"Error decoding JSON from {file_path}: {e}")
# return {}
# except Exception as e:
# logger.error(f"An unexpected error occurred while loading {file_path}: {e}")
# return {}
# Helper function to load the block catalog from a JSON file
def _load_block_catalog(block_type: str) -> Dict:
"""
Loads the Scratch block catalog named '{block_type}_blocks.json'
from the <project_root>/blocks/ folder. Returns {} on any error.
"""
catalog_path = BLOCKS_DIR / f"{block_type}.json"
try:
text = catalog_path.read_text() # will raise FileNotFoundError if missing
catalog = json.loads(text) # will raise JSONDecodeError if malformed
logger.info(f"Successfully loaded block catalog from {catalog_path}")
return catalog
except FileNotFoundError:
logger.error(f"Error: Block catalog file not found at {catalog_path}")
except json.JSONDecodeError as e:
logger.error(f"Error decoding JSON from {catalog_path}: {e}")
except Exception as e:
logger.error(f"Unexpected error loading {catalog_path}: {e}")
def get_block_by_opcode(catalog_data: dict, opcode: str) -> dict | None:
"""
Search a single catalog (with keys "description" and "blocks": List[dict])
for a block whose 'op_code' matches the given opcode.
Returns the block dict or None if not found.
"""
for block in catalog_data["blocks"]:
if block.get("op_code") == opcode:
return block
return None
# Helper function to find a block in all catalogs by opcode
def find_block_in_all(opcode: str, all_catalogs: list[dict]) -> dict | None:
"""
Search across multiple catalogs for a given opcode.
Returns the first matching block dict or None.
"""
for catalog in all_catalogs:
blk = get_block_by_opcode(catalog, opcode)
if blk is not None:
return blk
return None
# --- Global variable for the block catalog ---
# --- Global variable for the block catalog ---
ALL_SCRATCH_BLOCKS_CATALOG = {}
# BLOCK_CATALOG_PATH = r"blocks\blocks.json" # Define the path to your JSON file
# HAT_BLOCKS_PATH = r"blocks\hat_blocks.json" # Path to the hat blocks JSON file
# STACK_BLOCKS_PATH = r"blocks\stack_blocks.json" # Path to the stack blocks JSON file
# REPORTER_BLOCKS_PATH = r"blocks\reporter_blocks.json" # Path to the reporter blocks JSON file
# BOOLEAN_BLOCKS_PATH = r"blocks\boolean_blocks.json" # Path to the boolean blocks JSON file
# C_BLOCKS_PATH = r"blocks\c_blocks.json" # Path to the C blocks JSON file
# CAP_BLOCKS_PATH = r"blocks\cap_blocks.json" # Path to the cap blocks JSON file
# BLOCK_CATALOG_PATH = r"blocks/blocks.json"
# HAT_BLOCKS_PATH = r"blocks/hat_blocks.json"
# STACK_BLOCKS_PATH = r"blocks/stack_blocks.json"
# REPORTER_BLOCKS_PATH = r"blocks/reporter_blocks.json"
# BOOLEAN_BLOCKS_PATH = r"blocks/boolean_blocks.json"
# C_BLOCKS_PATH = r"blocks/c_blocks.json"
# CAP_BLOCKS_PATH = r"blocks/cap_blocks.json"
BLOCK_CATALOG_PATH = "blocks" # Define the path to your JSON file
HAT_BLOCKS_PATH = "hat_blocks" # Path to the hat blocks JSON file
STACK_BLOCKS_PATH = "stack_blocks" # Path to the stack blocks JSON file
REPORTER_BLOCKS_PATH = "reporter_blocks" # Path to the reporter blocks JSON file
BOOLEAN_BLOCKS_PATH = "boolean_blocks" # Path to the boolean blocks JSON file
C_BLOCKS_PATH = "c_blocks" # Path to the C blocks JSON file
CAP_BLOCKS_PATH = "cap_blocks" # Path to the cap blocks JSON file
# Load the block catalogs from their respective JSON files
hat_block_data = _load_block_catalog(HAT_BLOCKS_PATH)
# hat_description = hat_block_data["description"]
hat_description = hat_block_data.get("description", "No description available")
# hat_opcodes_functionalities = "\n".join([f" - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in hat_block_data["blocks"]])
hat_opcodes_functionalities = "\n".join([
f" - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
for block in hat_block_data.get("blocks", [])
]) if isinstance(hat_block_data.get("blocks"), list) else " No blocks information available."
print("Hat blocks loaded successfully.", hat_description)
boolean_block_data = _load_block_catalog(BOOLEAN_BLOCKS_PATH)
boolean_description = boolean_block_data["description"]
# boolean_opcodes_functionalities = "\n".join([f" - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in boolean_block_data["blocks"]])
boolean_opcodes_functionalities = "\n".join([
f" - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
for block in boolean_block_data.get("blocks", [])
]) if isinstance(boolean_block_data.get("blocks"), list) else " No blocks information available."
c_block_data = _load_block_catalog(C_BLOCKS_PATH)
c_description = c_block_data["description"]
# c_opcodes_functionalities = "\n".join([f" - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in c_block_data["blocks"]])
c_opcodes_functionalities = "\n".join([
f" - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
for block in c_block_data.get("blocks", [])
]) if isinstance(c_block_data.get("blocks"), list) else " No blocks information available."
cap_block_data = _load_block_catalog(CAP_BLOCKS_PATH)
cap_description = cap_block_data["description"]
# cap_opcodes_functionalities = "\n".join([f" - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in cap_block_data["blocks"]])
cap_opcodes_functionalities = "\n".join([
f" - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
for block in cap_block_data.get("blocks", [])
]) if isinstance(cap_block_data.get("blocks"), list) else " No blocks information available."
reporter_block_data = _load_block_catalog(REPORTER_BLOCKS_PATH)
reporter_description = reporter_block_data["description"]
# reporter_opcodes_functionalities = "\n".join([f" - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in reporter_block_data["blocks"]])
reporter_opcodes_functionalities = "\n".join([
f" - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
for block in reporter_block_data.get("blocks", [])
]) if isinstance(reporter_block_data.get("blocks"), list) else " No blocks information available."
stack_block_data = _load_block_catalog(STACK_BLOCKS_PATH)
stack_description = stack_block_data["description"]
# stack_opcodes_functionalities = "\n".join([f" - Opcode: {block['op_code']}, functionality: {block['functionality']} example: standalone use: {block['example_standalone']}" for block in stack_block_data["blocks"]])
stack_opcodes_functionalities = "\n".join([
f" - Opcode: {block.get('op_code', 'N/A')}, functionality: {block.get('functionality', 'N/A')}, example: standalone use {block.get('example_standalone', 'N/A')}"
for block in stack_block_data.get("blocks", [])
]) if isinstance(stack_block_data.get("blocks"), list) else " No blocks information available."
# This makes ALL_SCRATCH_BLOCKS_CATALOG available globally
ALL_SCRATCH_BLOCKS_CATALOG = _load_block_catalog(BLOCK_CATALOG_PATH)
# Helper function to extract JSON from LLM response
def extract_json_from_llm_response(raw_response: str) -> dict:
# --- 1) Pull out the JSON code‑block if present ---
md = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", raw_response)
json_string = md.group(1).strip() if md else raw_response
# --- 2) Trim to the outermost { … } so we drop any prefix/suffix junk ---
first, last = json_string.find('{'), json_string.rfind('}')
if 0 <= first < last:
json_string = json_string[first:last+1]
# --- 3) PRE‑CLEANUP: remove stray assistant{…}, rogue assistant keys, fix boolean quotes ---
json_string = re.sub(r'\b\w+\s*{', '{', json_string)
json_string = re.sub(r'"assistant"\s*:', '', json_string)
json_string = re.sub(r'\b(false|true)"', r'\1', json_string)
logger.debug("Ran pre‑cleanup for stray tokens and boolean quotes.")
# --- 3.1) Fix stray inner quotes at start of name/list values ---
# e.g., { "name": " \"recent_scoress\"", ... } → "recent_scoress"
json_string = re.sub(
r'("name"\s*:\s*")\s*"',
r'\1',
json_string
)
# --- 4) Escape all embedded quotes in any `logic` value up to the next key ---
def _esc(m):
prefix, body = m.group(1), m.group(2)
return prefix + body.replace('"', r'\"')
json_string = re.sub(
r'("logic"\s*:\s*")([\s\S]+?)(?=",\s*"[A-Za-z_]\w*"\s*:\s*)',
_esc,
json_string
)
logger.debug("Escaped embedded quotes in logic fields.")
logger.debug("Quoted unquoted keys.")
# --- 6) Remove trailing commas before } or ] ---
json_string = re.sub(r',\s*(?=[}\],])', '', json_string)
json_string = re.sub(r',\s*,', ',', json_string)
logger.debug("Removed trailing commas.")
# --- 7) Balance braces: drop extra } at end if needed ---
ob, cb = json_string.count('{'), json_string.count('}')
if cb > ob:
excess = cb - ob
json_string = json_string.rstrip()[:-excess]
logger.debug(f"Stripped {excess} extra closing brace(s).")
# --- 8) Escape literal newlines in *all* string values ---
json_string = re.sub(
r'"((?:[^"\\]|\\.)*?)"',
lambda m: '"' + m.group(1).replace('\n', '\\n').replace('\r', '\\r') + '"',
json_string,
flags=re.DOTALL
)
logger.debug("Escaped newlines in strings.")
# --- 9) Final parse attempt ---
try:
return json.loads(json_string)
except json.JSONDecodeError:
logger.error("Sanitized JSON still invalid:\n%s", json_string)
raise
# Node 1: Logic updating if any issue here
def pseudo_generator_node(state: GameState):
logger.info("--- Running plan_logic_aligner_node ---")
image = state.get("project_image", "")
project_json = state["project_json"]
# MODIFICATION 1: Include 'Stage' in the list of names to plan for.
# It's crucial to ensure 'Stage' is always present for its global role.
target_names = [t["name"] for t in project_json["targets"]]
refinement_prompt = f"""
You are an expert in Scratch 3.0 game development, specializing in understanding block relationships (stacked, nested).
"Analyze the Scratch code-block image and generate Pseudo-Code for what this logic appears to be doing."
From Image, you also have to detect a value of Key given in Text form "Script for: ". Below is the example
Example: "Script for: Bear", "Script for:" is a key and "Bear" is value and check if there is related target name available.
**Targets in Game (Sprites and Stage) available in project_json:** {', '.join(target_names)}
--- Scratch 3.0 Block Reference ---
### Hat Blocks
Description: {hat_description}
Blocks:
{hat_opcodes_functionalities}
### Boolean Blocks
Description: {boolean_description}
Blocks:
{boolean_opcodes_functionalities}
### C Blocks
Description: {c_description}
Blocks:
{c_opcodes_functionalities}
### Cap Blocks
Description: {cap_description}
Blocks:
{cap_opcodes_functionalities}
### Reporter Blocks
Description: {reporter_description}
Blocks:
{reporter_opcodes_functionalities}
### Stack Blocks
Description: {stack_description}
Blocks:
{stack_opcodes_functionalities}
-----------------------------------
Your task is to:
If you don't find any "Code-Blocks" then,
**Don't generate Pseudo Code, and pass the message "No Code-blocks"
If you find any "Code-Blocks" then,
1. **Refine the 'logic'**: Make it precise, accurate, and fully aligned with the Game Description. Use Scratch‑consistent verbs and phrasing. **Do NOT** use raw double‑quotes inside the logic string.
2. **Structural requirements**:
- **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
- **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
- **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
- **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
- **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
- **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
- **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
- **Operator expressions** must use explicit Scratch operator blocks, e.g.:
```
(([ballSpeed v]) * (1.1))
```
- **Every hat block script must end** with a final `end` on its own line.
3. **Pseudo‑code formatting**:
- Represent each block or nested block on its own line.
- Indent nested blocks by 4 spaces under their parent (`forever`, `if`, etc.).
- No comments or explanatory text—just the block sequence.
- a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
4. **Logic content**:
- Build clear flow for mechanics (movement, jumping, flying, scoring, collisions).
- Match each action closely to a Scratch block or tight sequence.
- Do **NOT** include any justification or comments—only the raw logic.
5. **Examples for reference**:
**Correct** pattern for a simple start script:
```
when green flag clicked
switch backdrop to [blue sky v]
set [score v] to (0)
show variable [score v]
broadcast [Game Start v]
end
```
**Correct** pattern for updating the high score variable handling:
```
when I receive [Game Over v]
if <((score)) > (([High Score v]))> then
set [High Score v] to ([score v])
end
switch backdrop to [Game Over v]
end
```
**Correct** pattern for level up and increase difficulty use:
```
when I receive [Level Up v]
change [level v] by (1)
set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
end
```
**Correct** pattern for jumping mechanics use:
```
when [space v] key pressed
if <((y position)) = (-100)> then
repeat (5)
change y by (100)
wait (0.1) seconds
change y by (-100)
wait (0.1) seconds
end
end
end
```
**Correct** pattern for continuos moving objects use:
```
when green flag clicked
go to x: (240) y: (-100)
set [speed v] to (-5)
show variable [speed v]
forever
change x by ([speed v])
if <((x position)) < (-240)> then
go to x: (240) y: (-100)
end
end
end
```
**Correct** pattern for continuos moving objects use:
```
when green flag clicked
go to x: (240) y: (-100)
set [speed v] to (-5)
show variable [speed v]
forever
change x by ([speed v])
if <((x position)) < (-240)> then
go to x: (240) y: (-100)
end
end
end
```
6. **Donot** add any explaination of logic or comments to justify or explain just put the logic content in the json.
7. **Output**:
Return **only** a JSON object, using double quotes everywhere:
```json
{{
"refined_logic":{{
"name_variable": 'Value of "Sript for: "',
"pseudocode":"…your fully‑formatted pseudo‑code here…",
}}
}}
```
"""
image_input = {
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image}"
}
}
content = [
{"type": "text", "text": refinement_prompt},
image_input
]
try:
# Invoke the main agent for logic refinement and relationship identification
response = agent.invoke({"messages": [{"role": "user", "content": content}]})
llm_output_raw = response["messages"][-1].content.strip()
print(f"llm_output_raw: {response}")
parsed_llm_output = extract_json_from_llm_response(llm_output_raw)
result = parsed_llm_output
print(f"result:\n\n {result}")
except json.JSONDecodeError as error_json:
# If JSON parsing fails, use the json resolver agent
correction_prompt = (
"Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
"It must be a JSON object with `refined_logic` (string) and `block_relationships` (array of objects).\n"
f"- **Error Details**: {error_json}\n\n"
"**Strict Instructions for your response:**\n"
"1. **ONLY** output the corrected JSON. Do not include any other text or explanations.\n"
"2. Ensure all keys and string values are enclosed in **double quotes**. Escape internal quotes (`\\`).\n"
"3. No trailing commas. Correct nesting.\n\n"
"Here is the problematic JSON string to correct:\n"
f"```json\n{llm_output_raw}\n```\n"
"Corrected JSON:\n"
)
try:
correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
corrected_output = extract_json_from_llm_response(correction_response['messages'][-1].content)
#block_relationships = corrected_output.get("block_relationships", [])
result = corrected_output
print(f"result:\n\n {result}")
except Exception as e_corr:
logger.error(f"Failed to correct JSON output for even after retry: {e_corr}")
# Update the original action_plan in the state with the refined version
state["pseudo_code"] = result
# with open("debug_state.json", "w", encoding="utf-8") as f:
# json.dump(state, f, indent=2, ensure_ascii=False)
print(f"[OVREALL REFINED PSEUDO CODE LOGIC]: {result}")
logger.info("Plan refinement and block relation analysis completed for all plans.")
return state
def overall_planner_node(state: GameState):
"""
Generates a comprehensive action plan for sprites, including detailed Scratch block information.
This node acts as an overall planner, leveraging knowledge of all block shapes and categories.
"""
logger.info("--- Running OverallPlannerNode ---")
project_json = state["project_json"]
raw = state.get("pseudo_code", {})
refined_logic_data = raw.get("refined_logic", {})
sprite_name = refined_logic_data.get("name_variable", "<unknown>")
pseudo = refined_logic_data.get("pseudocode", "")
# MODIFICATION 1: Include 'Stage' in the list of names to plan for.
# It's crucial to ensure 'Stage' is always present for its global role.
target_names = [t["name"] for t in project_json["targets"]]
# MODIFICATION 2: Get sprite positions, providing default for Stage as it doesn't have x,y
sprite_positions = {}
for target in project_json["targets"]:
if not target["isStage"]:
sprite_positions[target["name"]] = {"x": target.get("x", 0), "y": target.get("y", 0)}
else:
sprite_positions[target["name"]] = {"x": "N/A", "y": "N/A"} # Stage doesn't have positional coordinates
# declaration_plan = state["declaration_plan"]
planning_prompt = f"""
Generate a detailed action plan for the game's sprites and stage based on the given pseudo-code and sprite details for the given sprite name and .
Description:
**Sprite_name**: {sprite_name}
**and its corresponding Pseudo_code:**
'{pseudo}'
[Note: Make sure you just refine the pseudo code by correting mistake and adding the missing opcode if any and *Do not* generate any new logic]
----
**Targets in Game (Sprites and Stage) available in project_json:** {', '.join(target_names)}
--- Scratch 3.0 Block Reference ---
This section provides a comprehensive reference of Scratch 3.0 blocks, categorized by shape, including their opcodes and functional descriptions. Use this to accurately identify block types and behavior.
### Hat Blocks
Description: {hat_description}
Blocks:
{hat_opcodes_functionalities}
### Boolean Blocks
Description: {boolean_description}
Blocks:
{boolean_opcodes_functionalities}
### C Blocks
Description: {c_description}
Blocks:
{c_opcodes_functionalities}
### Cap Blocks
Description: {cap_description}
Blocks:
{cap_opcodes_functionalities}
### Reporter Blocks
Description: {reporter_description}
Blocks:
{reporter_opcodes_functionalities}
### Stack Blocks
Description: {stack_description}
Blocks:
{stack_opcodes_functionalities}
-----------------------------------
Your task is to use the `Sprite_name` given and `Pseudo_code` and add it to the specific target name and define the primary actions and movements.
The output should be a JSON object with a single key 'action_overall_flow'. Each key inside this object should be a sprite or 'Stage' name (e.g., 'Player', 'Enemy', 'Stage'), and its value must include a 'description' and a list of 'plans'.
Each plan must include a **single Scratch Hat Block** (e.g., 'event_whenflagclicked') to start scratch project and should contain:
1. **'event'**: the exact `opcode` of the hat block that initiates the logic.
[NOTE: INSTRUCTIONN TO FOLLOW IF PSEUDO_CODE HAVING PROBLEM ]
2. **'logic'**: a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
- Use 'forever: ...' or 'repeat(10): ...' to prefix repeating logic suitable taking reference from the C blocks.
- Use Scratch-consistent verbs: 'move', 'change', 'wait', 'hide', 'show', 'say', 'glide', etc.
- **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
- **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
- **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
- **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
- **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
- **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
- **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
- **Operator expressions** must use explicit Scratch operator blocks, e.g.:
```
(([ballSpeed v]) * (1.1))
```
- **Every hat block script must end** with a final `end` on its own line.
3. **Opcode Lists**: include relevant Scratch opcodes grouped under `motion`, `control`, `operator`, `sensing`, `looks`, `sounds`, `events`, and `data`. List only the non-empty categories. Use exact opcodes.
4. Few Example of content of logics inside for a specific plan as scratch pseudo-code:
- example 1[continues moving objects]:
```
when green flag clicked
go to x: (240) y: (-100)
set [speed v] to (-5)
show variable [speed v]
forever
change x by ([speed v])
if <((x position)) < (-240)> then
go to x: (240) y: (-100)
end
end
end
```
- example 2[jumping script of an plan]:
```
when [space v] key pressed
if <((y position)) = (-100)> then
repeat (5)
change y by (100)
wait (0.1) seconds
change y by (-100)
wait (0.1) seconds
end
end
end
```
- example 3 [pattern for level up and increase difficulty]:
```
when I receive [Level Up v]
change [level v] by (1)
set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
end
```
5. Use target names exactly as listed in `Targets in Game`. Do NOT rename or invent new targets.
6. Ensure the plan reflects accurate opcode usage derived strictly from the block reference above.
7. Few shot Example structure for 'action_overall_flow':
```json
{{
"action_overall_flow": {{
"Stage": {{
"description": "Background and global game state management, including broadcasts, rewards, and score.",
"plans": [
{{
"event": "event_whenflagclicked",
"logic": "when green flag clicked\n switch backdrop to [backdrop1 v]\n set [score v] to 0\n show variable [score v]\n broadcast [Game Start v]",
"motion": [],
"control": [],
"operator": [],
"sensing": [],
"looks": [
"looks_switchbackdropto"
],
"sounds": [],
"events": [
"event_broadcast"
],
"data": [
"data_setvariableto",
"data_showvariable"
]
}},
{{
"event": "event_whenbroadcastreceived",
"logic": "when I receive [Game Over v]\n if <(score) > (High Score)> then\n set [High Score v] to (score)\n end\n switch backdrop to [HighScore v]",
"motion": [],
"control": [
"control_if"
],
"operator": [
"operator_gt"
],
"sensing": [],
"looks": [
"looks_switchbackdropto"
],
"sounds": [],
"events": [],
"data": [
"data_setvariableto"
]
}}
]
}},
"Sprite1": {{
"description": "Main character (cat) actions",
"plans": [
{{
"event": "event_whenflagclicked",
"logic": "when green flag clicked\n go to x: 240 y: -100\n end\n.",
"motion": [
"motion_gotoxy"
],
"control": [],
"operator": [],
"sensing": [],
"looks": [],
"sounds": [],
"events": [],
"data": []
}},
{{
"event": "event_whenkeypressed",
"logic": "when [space v] key pressed\n repeat (10)\n change y by (20)\n wait (0.1) seconds\n change y by (-20)\n end",
"motion": [
"motion_changeyby"
],
"control": [
"control_repeat",
"control_wait"
],
"operator": [],
"sensing": [],
"looks": [],
"sounds": [],
"events": [],
"data": []
}}
]
}},
"soccer ball": {{
"description": "Obstacle movement and interaction",
"plans": [
{{
"event": "event_whenflagclicked",
"logic": "when green flag clicked\n go to x: 240 y: -135\n forever\n glide 2 seconds to x: -240 y: -135\n if <(x position) < -235> then\n set x to 240\n end\n if <touching [Sprite1 v]?> then\n broadcast [Game Over v]\n stop [all v]\n end\n end",
"motion": [
"motion_gotoxy",
"motion_glidesecstoxy",
"motion_xposition",
"motion_setx"
],
"control": [
"control_forever",
"control_if",
"control_stop"
],
"operator": [
"operator_lt"
],
"sensing": [
"sensing_istouching",
"sensing_touchingobjectmenu"
],
"looks": [],
"sounds": [],
"events": [
"event_broadcast"
],
"data": []
}}
]
}}
}}
}}
```
8. Based on the provided context, generate the `action_overall_flow`.
- Maintain the **exact JSON structure** shown above.
- All `logic` fields must be **clear and granular**.
- Only include opcode categories that contain relevant opcodes.
- Ensure that each opcode matches its intended Scratch functionality.
- If feedback suggests major change, **rethink the entire plan** for the affected sprite(s).
- If feedback is minor, make precise, minimal improvements only.
"""
try:
response = agent.invoke({"messages": [{"role": "user", "content": planning_prompt}]})
print("Raw response from LLM [OverallPlannerNode 1]:",response)
raw_response = response["messages"][-1].content#strip_noise(response["messages"][-1].content)
print("Raw response from LLM [OverallPlannerNode 2]:", raw_response) # Uncomment for debugging
# json debugging and solving
try:
overall_plan = extract_json_from_llm_response(raw_response)
except json.JSONDecodeError as error_json:
logger.error("Failed to extract JSON from LLM response. Attempting to correct the response.")
# Use the JSON resolver agent to fix the response
correction_prompt = (
"Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
"Carefully review the JSON for any errors, especially focusing on the reported error at:\n"
f"- **Error Details**: {error_json}\n\n"
"**Strict Instructions for your response:**\n"
"1. **ONLY** output the corrected JSON. Do not include any other text, comments, or explanations outside the JSON.\n"
"2. Ensure all property names (keys) are enclosed in **double quotes**.\n"
"3. Ensure string values are correctly enclosed in **double quotes** and any internal special characters (like newlines `\\n`, tabs `\\t`, backslashes `\\\\`, or double quotes `\\`) are properly **escaped**.\n"
"4. Verify that there are **no extra commas**, especially between key-value pairs or after the last element in an object or array.\n"
"5. Ensure proper nesting and matching of curly braces `{}` and square brackets `[]`.\n"
"6. **Crucially, remove any extraneous characters or duplicate closing braces outside the main JSON object.**\n"
"7. The corrected JSON must be a **complete and valid** JSON object.\n\n"
"Here is the problematic JSON string to correct:\n"
"```json\n"
f"{raw_response}\n"
"```\n"
"Corrected JSON:\n"
)
correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
print(f"[JSON CORRECTOR RESPONSE AT OVERALLPLANNERNODE ]: {correction_response['messages'][-1].content}")
overall_plan= extract_json_from_llm_response(correction_response['messages'][-1].content)#strip_noise(correction_response["messages"][-1].content))
state["action_plan"] = overall_plan
logger.info("Overall plan generated by OverallPlannerNode.")
# with open("debug_state.json", "w", encoding="utf-8") as f:
# json.dump(state, f, indent=2, ensure_ascii=False)
return state
except Exception as e:
logger.error(f"Error in OverallPlannerNode: {e}")
raise
def refined_planner_node(state: GameState):
"""
Refines the action plan based on validation feedback and game description.
"""
logger.info("--- Running RefinedPlannerNode ---")
raw = state.get("pseudo_code", {})
refined_logic_data = raw.get("refined_logic", {})
sprite_name = refined_logic_data.get("name_variable", "<unknown>")
pseudo = refined_logic_data.get("pseudocode", "")
#detailed_game_description = state.get("detailed_game_description", state.get("description", "A game."))
current_action_plan = state.get("action_plan", {})
print(f"[current_action_plan before refinement] on ({state.get('iteration_count', 0)}): {json.dumps(current_action_plan, indent=2)}")
plan_validation_feedback = state.get("plan_validation_feedback", "No specific feedback provided. Assume general refinement is needed.")
project_json = state["project_json"]
target_names = [t["name"] for t in project_json["targets"]]
# MODIFICATION 2: Get sprite positions, providing default for Stage as it doesn't have x,y
sprite_positions = {}
for target in project_json["targets"]:
if not target["isStage"]:
sprite_positions[target["name"]] = {"x": target.get("x", 0), "y": target.get("y", 0)}
else:
sprite_positions[target["name"]] = {"x": "N/A", "y": "N/A"} # Stage doesn't have positional coordinates
#declaration_plan = state["declaration_plan"]
refinement_prompt = f"""
Refine and correct the JSON object `action_overall_flow` so that it fully aligns with the detailed game description, sprite positions, variable/broadcast declarations, and Scratch 3.0 block reference—while also validating for common formatting or opcode errors.
Here is the overall script available:
**Sprite name**: {sprite_name}
**and its corresponding Pseudo_code:**
'{pseudo}'
[Note: Make sure you just refine the pseudo code by correting mistake and adding the missing opcode if any and *Do not* generate any new logic]
---
**Targets in Game (Sprites and Stage):** {', '.join(target_names)}
**Current action plan:**
{current_action_plan}
**Validation Feedback:**
'{plan_validation_feedback}'
--- Scratch 3.0 Block Reference ---
### Hat Blocks
{hat_opcodes_functionalities}
### Boolean Blocks
{boolean_opcodes_functionalities}
### C Blocks
{c_opcodes_functionalities}
### Cap Blocks
{cap_opcodes_functionalities}
### Reporter Blocks
{reporter_opcodes_functionalities}
### Stack Blocks
{stack_opcodes_functionalities}
-----------------------------------
* **Your task is to align to description, refine and correct the JSON object 'action_overall_flow'.**
Use sprite names exactly as provided in `sprite_names` (e.g., 'Sprite1', 'soccer ball'); and also the stage, do **NOT** rename them.
1. **'event'**: the exact `opcode` of the hat block that initiates the logic.
2. **'logic'**: a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
- Do **NOT** include any justification or comments—only the raw logic.
- Use 'forever: ...' or 'repeat(10): ...' to prefix repeating logic suitable taking reference from the C blocks.
- Use Scratch-consistent verbs: 'move', 'change', 'wait', 'hide', 'show', 'say', 'glide', etc.
- **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
- **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
- **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
- **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
- **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
- **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
- **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
- **Operator expressions** must use explicit Scratch operator blocks, e.g.:
```
(([ballSpeed v]) * (1.1))
```
- **Every hat block script must end** with a final `end` on its own line.
3. **Validation & Formatting Checks**
- **Opcode Coverage**: Ensure every action in `logic` has a matching opcode in the lists.
- **Bracket Nesting**: Confirm every `(` has a matching `)`, e.g., `(pick random (100) to (-100))`.
- **Operator Formatting**: Validate that operators use Scratch operator blocks, not inline math.
- **Common Errors**:
- `pick random (100,-100)` → `(pick random (100) to (-100))`
- Missing `end` at script conclusion
- Unwrapped reporter inputs or Boolean tests
4. **Opcode Lists**: include relevant Scratch opcodes grouped under `motion`, `control`, `operator`, `sensing`, `looks`, `sounds`, `events`, and `data`. List only the non-empty categories. Use exact opcodes .
5. Few Example of content of logics inside for a specific plan as scratch pseudo-code:
- example 1[continues moving objects]:
```
when green flag clicked
go to x: (240) y: (-100)
set [speed v] to (-5)
show variable [speed v]
forever
change x by ([speed v])
if <((x position)) < (-240)> then
go to x: (240) y: (-100)
end
end
end
```
- example 2[jumping script of an plan]:
```
when [space v] key pressed
if <((y position)) = (-100)> then
repeat (5)
change y by (100)
wait (0.1) seconds
change y by (-100)
wait (0.1) seconds
end
end
end
```
- example 3 [pattern for level up and increase difficulty]:
```
when I receive [Level Up v]
change [level v] by (1)
set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
end
```
6. Use target names exactly as listed in `Targets in Game`. Do NOT rename or invent new targets.
7. Ensure the plan reflects accurate opcode usage derived strictly from the block reference above.
8. Few shot Example structure for 'action_overall_flow':
```json
{{
"action_overall_flow": {{
"Stage": {{
"description": "Background and global game state management, including broadcasts, rewards, and score.",
"plans": [
{{
"event": "event_whenflagclicked",
"logic": "when green flag clicked\n switch backdrop to [backdrop1 v]\n set [score v] to 0\n show variable [score v]\n broadcast [Game Start v]",
"motion": [],
"control": [],
"operator": [],
"sensing": [],
"looks": [
"looks_switchbackdropto"
],
"sounds": [],
"events": [
"event_broadcast"
],
"data": [
"data_setvariableto",
"data_showvariable"
]
}},
{{
"event": "event_whenbroadcastreceived",
"logic": "when I receive [Game Over v]\n if <(score) > (High Score)> then\n set [High Score v] to (score)\n end\n switch backdrop to [HighScore v]",
"motion": [],
"control": [
"control_if"
],
"operator": [
"operator_gt"
],
"sensing": [],
"looks": [
"looks_switchbackdropto"
],
"sounds": [],
"events": [],
"data": [
"data_setvariableto"
]
}}
]
}},
"Sprite1": {{
"description": "Main character (cat) actions",
"plans": [
{{
"event": "event_whenflagclicked",
"logic": "when green flag clicked\n go to x: 240 y: -100\n end\n.",
"motion": [
"motion_gotoxy"
],
"control": [],
"operator": [],
"sensing": [],
"looks": [],
"sounds": [],
"events": [],
"data": []
}},
{{
"event": "event_whenkeypressed",
"logic": "when [space v] key pressed\n repeat (10)\n change y by (20)\n wait (0.1) seconds\n change y by (-20)\n end",
"motion": [
"motion_changeyby"
],
"control": [
"control_repeat",
"control_wait"
],
"operator": [],
"sensing": [],
"looks": [],
"sounds": [],
"events": [],
"data": []
}}
]
}},
"soccer ball": {{
"description": "Obstacle movement and interaction",
"plans": [
{{
"event": "event_whenflagclicked",
"logic": "when green flag clicked\n go to x: 240 y: -135\n forever\n glide 2 seconds to x: -240 y: -135\n if <(x position) < -235> then\n set x to 240\n end\n if <touching [Sprite1 v]?> then\n broadcast [Game Over v]\n stop [all v]\n end\n end",
"motion": [
"motion_gotoxy",
"motion_glidesecstoxy",
"motion_xposition",
"motion_setx"
],
"control": [
"control_forever",
"control_if",
"control_stop"
],
"operator": [
"operator_lt"
],
"sensing": [
"sensing_istouching",
"sensing_touchingobjectmenu"
],
"looks": [],
"sounds": [],
"events": [
"event_broadcast"
],
"data": []
}}
]
}}
}}
}}
```
9. Use the validation feedback to address errors, fill in missing logic, or enhance clarity.
example of few possible improvements: 1.event_whenflagclicked is used to control sprite but its used for actual start scratch project and reset scratch. 2. looping like forever used where we should use iterative. 3. missing of for variable we used in the block
- Maintain the **exact JSON structure** shown above.
- All `logic` fields must be **clear and granular**.
- Only include opcode categories that contain relevant opcodes.
- Ensure that each opcode matches its intended Scratch functionality.
- If feedback suggests major change, **rethink the entire plan** for the affected sprite(s).
- If feedback is minor, make precise, minimal improvements only.
"""
try:
response = agent.invoke({"messages": [{"role": "user", "content": refinement_prompt}]})
raw_response = response["messages"][-1].content#strip_noise(response["messages"][-1].content)
logger.info(f"Raw response from LLM [RefinedPlannerNode]: {raw_response[:500]}...")
# json debugging and solving
try:
refined_plan = extract_json_from_llm_response(raw_response)
except json.JSONDecodeError as error_json:
logger.error("Failed to extract JSON from LLM response. Attempting to correct the response.")
# Use the JSON resolver agent to fix the response
correction_prompt = (
"Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
"Carefully review the JSON for any errors, especially focusing on the reported error at:\n"
f"- **Error Details**: {error_json}\n\n"
"**Strict Instructions for your response:**\n"
"1. **ONLY** output the corrected JSON. Do not include any other text, comments, or explanations outside the JSON.\n"
"2. Ensure all property names (keys) are enclosed in **double quotes**.\n"
"3. Ensure string values are correctly enclosed in **double quotes** and any internal special characters (like newlines `\\n`, tabs `\\t`, backslashes `\\\\`, or double quotes `\\`) are properly **escaped**.\n"
"4. IN `logic` field make sure content enclosed in **double quotes** should not have invalid **double quotes**, **eliminate** all quotes inside the content if any. "
"4. Verify that there are **no extra commas**, especially between key-value pairs or after the last element in an object or array.\n"
"5. Ensure proper nesting and matching of curly braces `{}` and square brackets `[]`.\n"
"6. **Crucially, remove any extraneous characters or duplicate closing braces outside the main JSON object.**\n" # Added instruction
"7. The corrected JSON must be a **complete and valid** JSON object.\n\n"
"Here is the problematic JSON string to correct:\n"
"```json\n"
f"{raw_response}\n"
"```\n"
"Corrected JSON:\n"
)
correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
print(f"[JSON CORRECTOR RESPONSE AT REFINEPLANNER ]: {correction_response['messages'][-1].content}")
refined_plan = extract_json_from_llm_response(correction_response["messages"][-1].content)#strip_noise(correction_response["messages"][-1].content))
logger.info("Refined plan corrected by JSON resolver agent.")
if refined_plan:
#state["action_plan"] = refined_plan.get("action_overall_flow", {}) # Update to the key 'action_overall_flow' [error]
state["action_plan"] = refined_plan #.get("action_overall_flow", {}) # Update the main the prompt includes updated only
logger.info("Action plan refined by RefinedPlannerNode.")
else:
logger.warning("RefinedPlannerNode did not return a valid 'action_overall_flow' structure. Keeping previous plan.")
print("[Refined Action Plan]:", json.dumps(state["action_plan"], indent=2))
#print("[current state after refinement]:", json.dumps(state, indent=2))
# with open("debug_state.json", "w", encoding="utf-8") as f:
# json.dump(state, f, indent=2, ensure_ascii=False)
return state
except Exception as e:
logger.error(f"Error in RefinedPlannerNode: {e}")
raise
def plan_opcode_counter_node(state: Dict[str, Any]) -> Dict[str, Any]:
"""
For each plan in state["action_plan"], calls the LLM agent
to analyze the `logic` string and return a list of {opcode, count} for each category.
"""
logger.info("=== Running OPCODE COUTER LOGIC with LLM counts ===")
#game_description = state.get("description", "No game description provided.")
sprite_name = {}
project_json_targets = state.get("project_json", {}).get("targets", [])
for target in project_json_targets:
sprite_name[target["name"]] = target["name"]
action_flow = state.get("action_plan", {})
if action_flow.get("action_overall_flow", {}) == {}:
plan_data = action_flow.items()
else:
plan_data = action_flow.get("action_overall_flow", {}).items()
refined_flow: Dict[str, Any] = {}
for sprite, sprite_data in plan_data:
refined_plans = []
for plan in sprite_data.get("plans", []):
logic = plan.get("logic", "")
event = plan.get("event", "")
# These are for guiding the LLM, not for the final output format directly
opcodes_from_plan = {
"motion": plan.get("motion", []),
"control": plan.get("control", []),
"operator": plan.get("operator", []),
"sensing": plan.get("sensing", []),
"looks": plan.get("looks", []),
"sounds": plan.get("sounds", []),
"events": plan.get("events", []) + ([event] if isinstance(event, str) else []),
"data": plan.get("data", []),
}
refinement_prompt = f"""
You are a Scratch 3.0 expert with deep knowledge of block types, nesting and stack relationships.
Your job: read the plan logic below and decide exactly which blocks (and how many of each) are required to implement it.
Review the following plan for '{sprite}' triggered by '{event}'.
--- Scratch 3.0 Block Reference ---
### Hat Blocks
Description: {hat_description}
Blocks:
{hat_opcodes_functionalities}
### Boolean Blocks
Description: {boolean_description}
Blocks:
{boolean_opcodes_functionalities}
### C Blocks
Description: {c_description}
Blocks:
{c_opcodes_functionalities}
### Cap Blocks
Description: {cap_description}
Blocks:
{cap_opcodes_functionalities}
### Reporter Blocks
Description: {reporter_description}
Blocks:
{reporter_opcodes_functionalities}
### Stack Blocks
Description: {stack_description}
Blocks:
{stack_opcodes_functionalities}
-----------------------------------
Current Plan Details:
- Event (Hat Block Opcode): {event}
- Associated Opcodes by Category: {json.dumps(opcodes_from_plan, indent=2)}
── Game Context ──
Sprite: "{sprite}"
── Current Plan ──
Event (hat block): {event}
Logic (pseudo-Scratch): {logic}
Plan : {plan}
── Opcode Candidates ──
Motion: {opcodes_from_plan["motion"]}
Control: {opcodes_from_plan["control"]}
Operator: {opcodes_from_plan["operator"]}
Sensing: {opcodes_from_plan["sensing"]}
Looks: {opcodes_from_plan["looks"]}
Sounds: {opcodes_from_plan["sounds"]}
Events: {opcodes_from_plan["events"]}
Data: {opcodes_from_plan["data"]}
── Your Task ──
1. Analyze the “Logic” steps and choose exactly which opcodes are needed.
2. Return a top-level JSON object with a single key: "opcode_counts".
3. The value of "opcode_counts" should be a list of objects, where each object has "opcode": "<opcode_name>" and "count": <integer>.
4. Ensure the list includes the hat block for this plan (e.g., event_whenflagclicked, event_whenkeypressed, event_whenbroadcastreceived) with a count of 1.
5. The order of opcodes within the "opcode_counts" list does not matter.
6. If any plan logic is None do not generate the opcode_counts for it.
7. Use only double quotes and ensure valid JSON.
Example output:
**example 1**
```json
{{
"opcode_counts":[
{{"opcode":"motion_gotoxy","count":1}},
{{"opcode":"control_forever","count":1}},
{{"opcode":"control_if","count":1}},
{{"opcode":"looks_switchbackdropto","count":1}},
{{"opcode":"event_whenflagclicked","count":1}},
{{"opcode":"event_broadcast","count":1}},
{{"opcode":"data_setvariableto","count":2}},
{{"opcode":"data_showvariable","count":2}}
]
}}
```
**example 2**
```json
{{
"opcode_counts":[
{{"opcode":"motion_gotoxy","count":1}},
{{"opcode":"motion_glidesecstoxy","count":1}},
{{"opcode":"motion_xposition","count":1}},
{{"opcode":"motion_setx","count":1}},
{{"opcode":"control_forever","count":1}},
{{"opcode":"control_if","count":2}},
{{"opcode":"operator_lt","count":1}},
{{"opcode":"sensing_istouching","count":1}},
{{"opcode":"event_whenflagclicked","count":1}},
{{"opcode":"event_broadcast","count":1}}
]
}}
```
"""
try:
response = agent.invoke({"messages": [{"role": "user", "content": refinement_prompt}]})
llm_output = response["messages"][-1].content
llm_json = extract_json_from_llm_response(llm_output)
logger.info(f"Successfully analyze the opcode requirement for {sprite} - {event}.")
except json.JSONDecodeError as error_json:
logger.error(f"JSON Decode Error for {sprite} - {event}: {error_json}. Attempting correction.")
correction_prompt = (
"Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
"It must be a JSON object with a single key `opcode_counts` containing a list of objects like {{'opcode': '<opcode_name>', 'count': <integer>}}.\n"
f"- **Error Details**: {error_json}\n\n"
"**Strict Instructions for your response:**\n"
"1. **ONLY** output the corrected JSON. Do not include any other text or explanations.\n"
"2. Ensure all keys and string values are enclosed in **double quotes**. Escape internal quotes (`\\`).\n"
"3. No trailing commas. Correct nesting.\n\n"
"Here is the problematic JSON string to correct:\n"
f"```json\n{llm_output}\n```\n"
"Corrected JSON:\n"
)
try:
correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
llm_json = extract_json_from_llm_response(correction_response["messages"][-1].content)
logger.info(f"Successfully corrected JSON output for {sprite} - {event}.")
except Exception as e_corr:
logger.error(f"Failed to correct JSON output for {sprite} - {event} even after retry: {e_corr}")
continue
# Directly use the 'opcode_counts' list from the LLM's output
plan["opcode_counts"] = llm_json.get("opcode_counts", [])
# Optionally, you can remove the individual category lists from the plan
# if they are no longer needed after the LLM provides the consolidated list.
# for key in ["motion", "control", "operator", "sensing", "looks", "sounds", "events", "data"]:
# if key in plan:
# del plan[key]
refined_plans.append(plan)
refined_flow[sprite] = {
"description": sprite_data.get("description", ""),
"plans": refined_plans
}
if refined_flow:
state["action_plan"] = refined_flow
logger.info("logic aligned by logic_aligner_Node.")
state["temporary_node"] = refined_flow
#state["temporary_node"] = refined_flow
print(f"[OPCODE COUTER LOGIC]: {refined_flow}")
logger.info("=== OPCODE COUTER LOGIC completed ===")
return state
# Node 10:Function based block builder node
# def overall_block_builder_node_2(state: dict):
# logger.info("--- Running OverallBlockBuilderNode ---")
# project_json = state["project_json"]
# targets = project_json["targets"]
# # --- Sprite and Stage Target Mapping ---
# sprite_map = {target["name"]: target for target in targets if not target["isStage"]}
# stage_target = next((target for target in targets if target["isStage"]), None)
# if stage_target:
# sprite_map[stage_target["name"]] = stage_target
# action_plan = state.get("action_plan", {})
# print("[Overall Action Plan received at the block generator]:", json.dumps(action_plan, indent=2))
# if not action_plan:
# logger.warning("No action plan found in state. Skipping OverallBlockBuilderNode.")
# return state
# # Initialize offsets for script placement on the Scratch canvas
# script_y_offset = {}
# script_x_offset_per_sprite = {name: 0 for name in sprite_map.keys()}
# # This handles potential variations in the action_plan structure.
# if action_plan.get("action_overall_flow", {}) == {}:
# plan_data = action_plan.items()
# else:
# plan_data = action_plan.get("action_overall_flow", {}).items()
# # --- Extract global project context for LLM ---
# all_sprite_names = list(sprite_map.keys())
# all_variable_names = {}
# all_list_names = {}
# all_broadcast_messages = {}
# for target in targets:
# for var_id, var_info in target.get("variables", {}).items():
# all_variable_names[var_info[0]] = var_id # Store name -> ID mapping (e.g., "myVariable": "myVarId123")
# for list_id, list_info in target.get("lists", {}).items():
# all_list_names[list_info[0]] = list_id # Store name -> ID mapping
# for broadcast_id, broadcast_name in target.get("broadcasts", {}).items():
# all_broadcast_messages[broadcast_name] = broadcast_id # Store name -> ID mapping
# # --- Process each sprite's action plan ---
# for sprite_name, sprite_actions_data in plan_data:
# if sprite_name in sprite_map:
# current_sprite_target = sprite_map[sprite_name]
# if "blocks" not in current_sprite_target:
# current_sprite_target["blocks"] = {}
# if sprite_name not in script_y_offset:
# script_y_offset[sprite_name] = 0
# for plan_entry in sprite_actions_data.get("plans", []):
# logic_sequence = str(plan_entry["logic"])
# opcode_counts = plan_entry.get("opcode_counts", {})
# try:
# generated_blocks=block_builder(opcode_counts,logic_sequence)
# if "blocks" in generated_blocks and isinstance(generated_blocks["blocks"], dict):
# logger.warning(f"LLM returned nested 'blocks' key for {sprite_name}. Unwrapping.")
# generated_blocks = generated_blocks["blocks"]
# # Update block positions for top-level script
# for block_id, block_data in generated_blocks.items():
# if block_data.get("topLevel"):
# block_data["x"] = script_x_offset_per_sprite.get(sprite_name, 0)
# block_data["y"] = script_y_offset[sprite_name]
# script_y_offset[sprite_name] += 150 # Increment for next script
# current_sprite_target["blocks"].update(generated_blocks)
# print(f"[current_sprite_target block updated]: {current_sprite_target['blocks']}")
# state["iteration_count"] = 0
# logger.info(f"Action blocks added for sprite '{sprite_name}' by OverallBlockBuilderNode.")
# except Exception as e:
# logger.error(f"Error generating blocks for sprite '{sprite_name}': {e}")
# state["project_json"] = project_json
# # with open("debug_state.json", "w", encoding="utf-8") as f:
# # json.dump(state, f, indent=2, ensure_ascii=False)
# return state
# Node 10:Function based block builder node
def overall_block_builder_node_2(state: dict):
logger.info("--- Running OverallBlockBuilderNode ---")
project_json = state["project_json"]
targets = project_json["targets"]
# --- Sprite and Stage Target Mapping ---
sprite_map = {target["name"]: target for target in targets if not target["isStage"]}
stage_target = next((target for target in targets if target["isStage"]), None)
if stage_target:
sprite_map[stage_target["name"]] = stage_target
action_plan = state.get("action_plan", {})
print("[Overall Action Plan received at the block generator]:", json.dumps(action_plan, indent=2))
if not action_plan:
logger.warning("No action plan found in state. Skipping OverallBlockBuilderNode.")
return state
# Initialize offsets for script placement on the Scratch canvas
script_y_offset = {}
script_x_offset_per_sprite = {name: 0 for name in sprite_map.keys()}
# This handles potential variations in the action_plan structure.
if action_plan.get("action_overall_flow", {}) == {}:
plan_data = action_plan.items()
else:
plan_data = action_plan.get("action_overall_flow", {}).items()
# --- Extract global project context for LLM ---
all_sprite_names = list(sprite_map.keys())
all_variable_names = {}
all_list_names = {}
all_broadcast_messages = {}
for target in targets:
for var_id, var_info in target.get("variables", {}).items():
all_variable_names[var_info[0]] = var_id # Store name -> ID mapping (e.g., "myVariable": "myVarId123")
for list_id, list_info in target.get("lists", {}).items():
all_list_names[list_info[0]] = list_id # Store name -> ID mapping
for broadcast_id, broadcast_name in target.get("broadcasts", {}).items():
all_broadcast_messages[broadcast_name] = broadcast_id # Store name -> ID mapping
# --- Process each sprite's action plan ---
for sprite_name, sprite_actions_data in plan_data:
if sprite_name in sprite_map:
current_sprite_target = sprite_map[sprite_name]
if "blocks" not in current_sprite_target:
current_sprite_target["blocks"] = {}
if sprite_name not in script_y_offset:
script_y_offset[sprite_name] = 0
for plan_entry in sprite_actions_data.get("plans", []):
logic_sequence = str(plan_entry["logic"])
opcode_counts = plan_entry.get("opcode_counts", {})
try:
generated_blocks = block_builder(opcode_counts, logic_sequence)
# Ensure generated_blocks is a dictionary
if not isinstance(generated_blocks, dict):
logger.error(f"block_builder for sprite '{sprite_name}' returned non-dict type: {type(generated_blocks)}. Skipping block update.")
continue # Skip to next plan_entry if output is not a dictionary
if "blocks" in generated_blocks and isinstance(generated_blocks["blocks"], dict):
logger.warning(f"LLM returned nested 'blocks' key for {sprite_name}. Unwrapping.")
generated_blocks = generated_blocks["blocks"]
# Update block positions for top-level script
for block_id, block_data in generated_blocks.items():
if block_data.get("topLevel"):
block_data["x"] = script_x_offset_per_sprite.get(sprite_name, 0)
block_data["y"] = script_y_offset[sprite_name]
script_y_offset[sprite_name] += 150 # Increment for next script
current_sprite_target["blocks"].update(generated_blocks)
print(f"[current_sprite_target block updated]: {current_sprite_target['blocks']}")
state["iteration_count"] = 0
logger.info(f"Action blocks added for sprite '{sprite_name}' by OverallBlockBuilderNode.")
except Exception as e:
logger.error(f"Error generating blocks for sprite '{sprite_name}': {e}")
# Consider adding more specific error handling here if a malformed output
# from block_builder should cause a specific state change, but generally
# avoid nulling the entire project_json.
state["project_json"] = project_json
# with open("debug_state.json", "w", encoding="utf-8") as f:
# json.dump(state, f, indent=2, ensure_ascii=False)
return state
# # Node 11: Variable adder node
def variable_adder_node(state: GameState):
project_json = state["project_json"]
try:
updated_project_json = variable_adder_main(project_json)
state["project_json"]=updated_project_json
return state
except Exception as e:
logger.error(f"Error in variable adder node while updating project_json': {e}")
raise
scratch_keywords = [
"move", "turn", "wait", "repeat", "if", "else", "broadcast",
"glide", "change", "forever", "when", "switch",
"next costume", "set", "show", "hide", "play sound",
"go to", "x position", "y position", "think", "say",
"variable", "stop", "clone",
"touching", "sensing", "pen", "clear","Scratch","Code","scratch blocks"
]
#def extract_images_from_pdf(pdf_path: Path, json_base_dir: Path, image_base_dir: Path):
#def extract_images_from_pdf(pdf_path: Path, json_base_dir: Path):
def extract_images_from_pdf(pdf_path: Path):
''' Extract images from PDF and generate structured sprite JSON '''
try:
pdf_path = Path(pdf_path)
pdf_filename = pdf_path.stem # e.g., "scratch_crab"
pdf_dir_path = str(pdf_path.parent).replace("/", "\\")
print("-------------------------------pdf_filename-------------------------------",pdf_filename)
print("-------------------------------pdf_dir_path-------------------------------",pdf_dir_path)
# Create subfolders under the provided base directories
# This will create paths like:
# /app/detected_images/pdf_filename/
# /app/json_data/pdf_filename/
extracted_image_subdir = DETECTED_IMAGE_DIR / pdf_filename
json_subdir = JSON_DIR / pdf_filename
extracted_image_subdir.mkdir(parents=True, exist_ok=True)
json_subdir.mkdir(parents=True, exist_ok=True)
print("-------------------------------extracted_image_subdir-------------------------------",extracted_image_subdir)
print("-------------------------------json_subdir-------------------------------",json_subdir)
# Output paths (now using Path objects directly)
output_json_path = json_subdir / "extracted.json"
final_json_path = json_subdir / "extracted_sprites.json" # Path to extracted_sprites.json
final_json_path_2 = json_subdir / "extracted_sprites_2.json"
print("-------------------------------output_json_path-------------------------------",output_json_path)
print("-------------------------------final_json_path-------------------------------",final_json_path)
print("-------------------------------final_json_path_2-------------------------------",final_json_path_2)
try:
elements = partition_pdf(
filename=str(pdf_path), # partition_pdf might expect a string
strategy="hi_res",
extract_image_block_types=["Image"],
extract_image_block_to_payload=True,
)
except Exception as e:
raise RuntimeError(
f"❌ Failed to extract images from PDF: {str(e)}")
try:
with open(output_json_path, "w") as f:
json.dump([element.to_dict()
for element in elements], f, indent=4)
except Exception as e:
raise RuntimeError(f"❌ Failed to write extracted.json: {str(e)}")
try:
# Display extracted images
with open(output_json_path, 'r') as file:
file_elements = json.load(file)
except Exception as e:
raise RuntimeError(f"❌ Failed to read extracted.json: {str(e)}")
# Prepare manipulated sprite JSON structure
manipulated_json = {}
# SET A SYSTEM PROMPT
system_prompt = """
You are an expert in visual scene understanding.
Your Job is to analyze an image and respond acoording if asked for name give simple name by analyzing it and if ask for descrption generate a short description covering its elements.
Guidelines:
- Focus only the images given in Square Shape.
- Don't Consider Blank areas in Image as.
- Don't include generic summary or explanation outside the fields.
Return only string.
"""
agent = create_react_agent(
model=llm,
tools=[],
prompt=system_prompt
)
# If JSON already exists, load it and find the next available Sprite number
if final_json_path.exists(): # Use Path.exists()
with open(final_json_path, "r") as existing_file:
manipulated = json.load(existing_file)
# Determine the next available index (e.g., Sprite 4 if 1–3 already exist)
existing_keys = [int(k.replace("Sprite ", ""))
for k in manipulated.keys()]
start_count = max(existing_keys, default=0) + 1
else:
start_count = 1
sprite_count = start_count
for i, element in enumerate(file_elements):
if "image_base64" in element["metadata"]:
try:
image_data = base64.b64decode(
element["metadata"]["image_base64"])
image = Image.open(BytesIO(image_data)).convert("RGB") # Use BytesIO here
image = upscale_image(image, scale=2)
# image.show(title=f"Extracted Image {i+1}")
# MODIFIED: Store image directly to BytesIO to avoid saving to disk if not needed
# and then converting back to base64.
img_buffer = BytesIO()
image.save(img_buffer, format="PNG")
img_bytes = img_buffer.getvalue()
img_base64 = base64.b64encode(img_bytes).decode("utf-8")
# Optionally save image to disk if desired for debugging/permanent storage
image_path = extracted_image_subdir / f"Sprite_{i+1}.png"
image.save(image_path)
prompt_combined = """
Analyze this image and return JSON with keys:# modify prompt for "name", if it detects "code-blocks only then give name as 'scratch-block'"
{
"name": "<short name or 'scratch blocks'>" ,
"description": "<short description>"
}
Guidelines:
- If image contains logical/code blocks from Scratch (e.g., move, turn, repeat, when clicked, etc.), use 'scratch-block' as the name.
- If image is a character, object, or backdrop, give an appropriate descriptive name instead.
- Avoid generic names like 'image1' or 'picture'.
- Keep the response strictly in JSON format.
"""
content = [
{"type": "text", "text": prompt_combined},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}}
]
response = agent.invoke({"messages": [{"role": "user", "content": content}]})
# Ensure response is handled correctly, it might be a string that needs json.loads
try:
# Assuming the agent returns a dictionary with 'messages' key,
# and the last message's content is the JSON string.
response_content_str = response.get("messages", [])[-1].content
result_json = json.loads(response_content_str)
except (json.JSONDecodeError, IndexError, AttributeError) as e:
logger.error(f"⚠️ Failed to parse agent response as JSON: {e}. Response was: {response}", exc_info=True)
result_json = {} # Default to empty dict if parsing fails
try:
name = result_json.get("name", "").strip()
description = result_json.get("description", "").strip()
except Exception as e:
logger.error(f"⚠️ Failed to extract name/description from result_json: {str(e)}", exc_info=True)
name = "unknown"
description = "unknown"
manipulated_json[f"Sprite {sprite_count}"] = {
"name": name,
"base64": element["metadata"]["image_base64"],
"file-path": pdf_dir_path,
"description": description
}
sprite_count += 1
except Exception as e:
logger.error(f"⚠️ Error processing Sprite {i+1}: {str(e)}", exc_info=True)
# Save manipulated JSON
with open(final_json_path, "w") as sprite_file:
json.dump(manipulated_json, sprite_file, indent=4)
def is_code_block(name: str) -> bool:
for kw in scratch_keywords:
if kw.lower() in name.lower():
return True
return False
# Filter out code block images
filtered_sprites = {}
for key, value in manipulated_json.items():
sprite_name = value.get("name", "")
if not is_code_block(sprite_name):
filtered_sprites[key] = value
else:
logger.info(f"🛑 Excluded code block-like image: {key}")
# Overwrite with filtered content
with open(final_json_path_2, "w") as sprite_file:
json.dump(filtered_sprites, sprite_file, indent=4)
# MODIFIED RETURN VALUE: Return the Path to the primary extracted_sprites.json file
# and the directory where it's located.
return final_json_path, json_subdir # Return the file path and its parent directory
except Exception as e:
raise RuntimeError(f"❌ Error in extract_images_from_pdf: {str(e)}")
def similarity_matching(input_json_path: str, project_folder: str) -> str:
logger.info("🔍 Running similarity matching…")
os.makedirs(project_folder, exist_ok=True)
# ----------------------------------------
# CHANGED: define normalized base-paths so startswith() checks work
backdrop_base_path = os.path.normpath(str(BACKDROP_DIR))
sprite_base_path = os.path.normpath(str(SPRITE_DIR))
# ----------------------------------------
project_json_path = os.path.join(project_folder, "project.json")
# ==============================
# READ SPRITE METADATA
# ==============================
with open(input_json_path, 'r') as f:
sprites_data = json.load(f)
sprite_ids, texts, sprite_base64 = [], [], []
for sid, sprite in sprites_data.items():
sprite_ids.append(sid)
texts.append("This is " + sprite.get("description", sprite.get("name", "")))
sprite_base64.append(sprite["base64"])
# =========================================
# Build the list of all candidate images
# =========================================
folder_image_paths = [
# backdrops
BACKDROP_DIR / "badroom3.sb3" / "8cc0b88d53345b3e337e8f028a32a4e7.png",
BACKDROP_DIR / "baseball2.sb3" / "7be1f5b3e682813dac1f297e52ff7dca.png",
BACKDROP_DIR / "beach_malibu.sb3" / "050615fe992a00d6af0e664e497ebf53.png",
BACKDROP_DIR / "castle2.sb3" / "951765ee7f7370f120c9df20b577c22f.png",
BACKDROP_DIR / "hall.sb3" / "ea86ca30b346f27ca5faf1254f6a31e3.png",
BACKDROP_DIR / "jungle.sb3" / "f4f908da19e2753f3ed679d7b37650ca.png",
# sprites
SPRITE_DIR / "Batter.sprite3" / "baseball_sprite_motion_1.png",
SPRITE_DIR / "Bear.sprite3" / "bear_motion_2.png",
SPRITE_DIR / "Beetle.sprite3" / "46d0dfd4ae7e9bfe3a6a2e35a4905eae.png",
SPRITE_DIR / "cat" / "cat_motion_1.png",
SPRITE_DIR / "Centaur.sprite3" / "2373556e776cad3ba4d6ee04fc34550b.png",
SPRITE_DIR / "Crab.sprite3" / "bear_element.png",
SPRITE_DIR / "Soccer Ball.sprite3" / "cat_football.png",
]
folder_image_paths = [os.path.normpath(str(p)) for p in folder_image_paths]
# =========================================
# -----------------------------------------
# Load reference embeddings from JSON
# -----------------------------------------
with open(f"{BLOCKS_DIR}/embeddings.json", "r") as f:
embedding_json = json.load(f)
img_matrix = np.array([img["embeddings"] for img in embedding_json])
# =========================================
# Decode & embed each sprite image
# =========================================
sprite_features = []
for b64 in sprite_base64:
if "," in b64:
b64 = b64.split(",", 1)[1]
img_bytes = base64.b64decode(b64)
pil_img = Image.open(BytesIO(img_bytes)).convert("RGB")
buf = BytesIO()
pil_img.save(buf, format="PNG")
buf.seek(0)
feats = clip_embd.embed_image([buf])[0]
sprite_features.append(feats)
sprite_matrix = np.vstack(sprite_features)
# =========================================
# Compute similarities & pick best match
# =========================================
similarity = np.matmul(sprite_matrix, img_matrix.T)
most_similar_indices = np.argmax(similarity, axis=1)
# =========================================
# Copy matched sprite assets + collect data
# =========================================
project_data = []
copied_folders = set()
for sprite_idx, matched_idx in enumerate(most_similar_indices):
matched_image_path = folder_image_paths[matched_idx]
matched_folder = os.path.dirname(matched_image_path)
# CHANGED: use our new normalized sprite_base_path
if not matched_folder.startswith(sprite_base_path):
continue
if matched_folder in copied_folders:
continue
copied_folders.add(matched_folder)
logger.info(f"Matched sprite: {matched_image_path}")
sprite_json_path = os.path.join(matched_folder, 'sprite.json')
if not os.path.exists(sprite_json_path):
logger.warning(f"No sprite.json in {matched_folder}")
continue
with open(sprite_json_path, 'r') as f:
sprite_info = json.load(f)
# copy all non‐matched files
for fname in os.listdir(matched_folder):
if fname in (os.path.basename(matched_image_path), 'sprite.json'):
continue
shutil.copy2(os.path.join(matched_folder, fname),
os.path.join(project_folder, fname))
project_data.append(sprite_info)
# =========================================
# Copy matched backdrop assets + collect
# =========================================
backdrop_data = []
for backdrop_idx, matched_idx in enumerate(most_similar_indices):
matched_image_path = folder_image_paths[matched_idx]
matched_folder = os.path.dirname(matched_image_path)
# CHANGED: use our new normalized backdrop_base_path
if not matched_folder.startswith(backdrop_base_path):
continue
logger.info(f"Matched backdrop: {matched_image_path}")
# copy non‐matched files
for fname in os.listdir(matched_folder):
if fname in (os.path.basename(matched_image_path), 'project.json'):
continue
shutil.copy2(os.path.join(matched_folder, fname),
os.path.join(project_folder, fname))
# append the stage‐target from its project.json
pj = os.path.join(matched_folder, 'project.json')
if os.path.exists(pj):
with open(pj, 'r') as f:
bd_json = json.load(f)
for tgt in bd_json.get("targets", []):
if tgt.get("isStage"):
backdrop_data.append(tgt)
else:
logger.warning(f"No project.json in {matched_folder}")
# =========================================
# Merge into final Scratch project.json
# =========================================
final_project = {
"targets": [], "monitors": [], "extensions": [],
"meta": {
"semver": "3.0.0",
"vm": "11.3.0",
"agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}
}
# sprites first
for spr in project_data:
if not spr.get("isStage", False):
final_project["targets"].append(spr)
# then backdrop as the Stage
if backdrop_data:
all_costumes, sounds = [], []
for i, bd in enumerate(backdrop_data):
all_costumes.extend(bd.get("costumes", []))
if i == 0:
sounds = bd.get("sounds", [])
stage_obj={
"isStage": True,
"name": "Stage",
"objName": "Stage",
"variables": {},
"lists": {},
"broadcasts": {},
"blocks": {},
"comments": {},
"currentCostume": 1 if len(all_costumes) > 1 else 0,
"costumes": all_costumes,
"sounds": sounds,
"volume": 100,
"layerOrder": 0,
"tempo": 60,
"videoTransparency": 50,
"videoState": "on",
"textToSpeechLanguage": None
}
final_project["targets"].insert(0, stage_obj)
with open(project_json_path, 'w') as f:
json.dump(final_project, f, indent=2)
return project_json_path
# for sprite_idx, matched_idx in enumerate(most_similar_indices):
# matched_image_path = folder_image_paths[matched_idx]
# matched_image_path = os.path.normpath(matched_image_path)
# print(" --------------------------------------1- matched_image_path ---------------------------------------",matched_image_path)
# matched_folder = os.path.dirname(matched_image_path)
# #folder_name = os.path.basename(matched_folder)
# print(" --------------------------------------1- matched_folder ---------------------------------------",matched_folder)
# if matched_folder in copied_folders:
# continue
# copied_folders.add(matched_folder)
# logger.info(f"Matched image path: {matched_image_path}")
# sprite_json_path = os.path.join(matched_folder, 'sprite.json')
# print(" --------------------------------------- sprite_json_path ---------------------------------------",sprite_json_path)
# if not os.path.exists(sprite_json_path):
# logger.warning(f"sprite.json not found in: {matched_folder}")
# continue
# with open(sprite_json_path, 'r') as f:
# sprite_data = json.load(f)
# # print(f"SPRITE DATA: \n{sprite_data}")
# # # Copy only non-matched files
# # for fname in os.listdir(matched_folder):
# # fpath = os.path.join(matched_folder, fname)
# # if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'sprite.json'}:
# # shutil.copy2(fpath, os.path.join(project_folder, fname))
# # # logger.info(f"Copied Sprite asset: {fname}")
# project_data.append(sprite_data)
# print(" --------------------------------------1- project_data ---------------------------------------",project_data)
# for fname in os.listdir(matched_folder):
# fpath = os.path.join(matched_folder, fname)
# dest_path = os.path.join(project_folder, fname)
# if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'sprite.json'}:
# shutil.copy2(fpath, dest_path)
# logger.info(f"🟢 Copied Sprite Asset: {fpath} → {dest_path}")
# # ================================================================== #
# # Loop through most similar images from Backdrops folder #
# # → Copy Backdrop assets (excluding matched image + project.json) #
# # → Load project.json and append its data to project_data #
# # ================================================================== #
# backdrop_data = [] # for backdrop-related entries
# for backdrop_idx, matched_idx in enumerate(most_similar_indices):
# matched_image_path = os.path.normpath(folder_image_paths[matched_idx])
# print(" --------------------------------------2- matched_image_path ---------------------------------------",matched_image_path)
# # Check if the match is from the Backdrops folder
# if matched_image_path.startswith(os.path.normpath(backdrop_images_path)):
# matched_folder = os.path.dirname(matched_image_path)
# print(" --------------------------------------2- matched_folder ---------------------------------------",matched_folder)
# folder_name = os.path.basename(matched_folder)
# logger.info(f"Backdrop matched image: {matched_image_path}")
# # Copy only non-matched files
# # for fname in os.listdir(matched_folder):
# # fpath = os.path.join(matched_folder, fname)
# # if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'project.json'}:
# # shutil.copy2(fpath, os.path.join(project_folder, fname))
# # # logger.info(f"Copied Backdrop asset: {fname}")
# for fname in os.listdir(matched_folder):
# fpath = os.path.join(matched_folder, fname)
# dest_path = os.path.join(project_folder, fname)
# if os.path.isfile(fpath) and fname not in {os.path.basename(matched_image_path), 'project.json'}:
# shutil.copy2(fpath, dest_path)
# logger.info(f"🟡 Copied Backdrop Asset: {fpath} → {dest_path}")
# # Append backdrop's project.json
# backdrop_json_path = os.path.join(matched_folder, 'project.json')
# print(" --------------------------------------2- backdrop_json_path ---------------------------------------",backdrop_json_path)
# if os.path.exists(backdrop_json_path):
# with open(backdrop_json_path, 'r') as f:
# backdrop_json_data = json.load(f)
# # print(f"SPRITE DATA: \n{backdrop_json_data}")
# if "targets" in backdrop_json_data:
# for target in backdrop_json_data["targets"]:
# if target.get("isStage") == True:
# backdrop_data.append(target)
# else:
# logger.warning(f"project.json not found in: {matched_folder}")
# # Merge JSON structure
# final_project = {
# "targets": [],
# "monitors": [],
# "extensions": [],
# "meta": {
# "semver": "3.0.0",
# "vm": "11.3.0",
# "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
# }
# }
# for sprite in project_data:
# if not sprite.get("isStage", False):
# final_project["targets"].append(sprite)
# if backdrop_data:
# all_costumes, sounds = [], []
# for idx, bd in enumerate(backdrop_data):
# all_costumes.extend(bd.get("costumes", []))
# if idx == 0 and "sounds" in bd:
# sounds = bd["sounds"]
# final_project["targets"].append({
# "isStage": True,
# "name": "Stage",
# "variables": {},
# "lists": {},
# "broadcasts": {},
# "blocks": {},
# "comments": {},
# "currentCostume": 1 if len(all_costumes) > 1 else 0,
# "costumes": all_costumes,
# "sounds": sounds,
# "volume": 100,
# "layerOrder": 0,
# "tempo": 60,
# "videoTransparency": 50,
# "videoState": "on",
# "textToSpeechLanguage": None
# })
# with open(project_json_path, 'w') as f:
# json.dump(final_project, f, indent=2)
# # logger.info(f"🎉 Final project saved: {project_json_path}")
# return project_json_path
def delay_for_tpm_node(state: GameState):
logger.info("--- Running DelayForTPMNode ---")
time.sleep(60) # Adjust the delay as needed
logger.info("Delay completed.")
return state
# Build the LangGraph workflow
workflow = StateGraph(GameState)
# Add all nodes to the workflow
workflow.add_node("time_delay_1", delay_for_tpm_node)
workflow.add_node("time_delay_2", delay_for_tpm_node)
workflow.add_node("time_delay_3", delay_for_tpm_node)
# workflow.add_node("time_delay_4", delay_for_tpm_node)
workflow.add_node("pseudo_generator", pseudo_generator_node)
workflow.add_node("plan_generator", overall_planner_node)
#workflow.add_node("logic_alignment", plan_logic_aligner_node)
#workflow.add_node("plan_verifier", plan_verification_node)
workflow.add_node("refined_planner", refined_planner_node) # Refines the action plan
workflow.add_node("opcode_counter", plan_opcode_counter_node)
workflow.add_node("block_builder", overall_block_builder_node_2)
# #workflow.add_node("variable_initializer", variable_adder_node)
workflow.set_entry_point("pseudo_generator")
workflow.add_edge("pseudo_generator","time_delay_1")
workflow.add_edge("time_delay_1","plan_generator")
workflow.add_edge("plan_generator","time_delay_2")
workflow.add_edge("time_delay_2",END)
workflow.add_edge("time_delay_2","refined_planner")
workflow.add_edge("refined_planner","time_delay_3")
workflow.add_edge("time_delay_3","opcode_counter")
workflow.add_edge("opcode_counter","block_builder")
workflow.add_edge("block_builder",END)
#workflow.add_edge("variable_initializer", END)
app_graph = workflow.compile()
# ============== Helper function to Upscale an Image ============== #
def upscale_image(image: Image.Image, scale: int = 2) -> Image.Image:
"""
Upscales a PIL image by a given scale factor.
"""
try:
width, height = image.size
new_size = (width * scale, height * scale)
upscaled_image = image.resize(new_size, Image.LANCZOS)
logger.info(f"✅ Upscaled image to {new_size}")
return upscaled_image
except Exception as e:
logger.error(f"❌ Error during image upscaling: {str(e)}")
return image
def create_sb3_archive(project_folder, project_id):
"""
Zips the project folder and renames it to an .sb3 file.
Args:
project_folder (str): The path to the directory containing the project.json and assets.
project_id (str): The unique ID for the project, used for naming the .sb3 file.
Returns:
str: The path to the created .sb3 file, or None if an error occurred.
"""
print(" --------------------------------------- create_sb3_archive INITIALIZE ---------------------------------------")
# output_filename = os.path.join("outputs", project_id)
#output_filename = OUTPUT_DIR / project_id
output_filename = GEN_PROJECT_DIR / project_id
print(" --------------------------------------- output_filename ---------------------------------------",output_filename)
zip_path = None
sb3_path = None
try:
zip_path = shutil.make_archive(output_filename, 'zip', root_dir=project_folder)
print(" --------------------------------------- zip_path_str ---------------------------------------", output_filename, project_folder)
logger.info(f"Project folder zipped to: {zip_path}")
# 2. Rename the .zip file to .sb3
sb3_path = f"{output_filename}.sb3"
os.rename(zip_path, sb3_path)
print(" --------------------------------------- rename paths ---------------------------------------", zip_path, sb3_path)
logger.info(f"Renamed {zip_path} to {sb3_path}")
return sb3_path
except Exception as e:
logger.error(f"Error creating SB3 archive for {project_id}: {e}")
# Clean up any partial files if an error occurs
if zip_path and os.path.exists(zip_path):
os.remove(zip_path)
if sb3_path and os.path.exists(sb3_path):
os.remove(sb3_path)
return sb3_path
@app.route('/')
def index():
return render_template('app_index.html')
@app.route("/download_sb3/<project_id>", methods=["GET"])
def download_sb3(project_id):
sb3_path = GEN_PROJECT_DIR / f"{project_id}.sb3"
if not sb3_path.exists():
return jsonify({"error": "Scratch project file not found"}), 404
return send_file(
sb3_path,
as_attachment=True,
download_name=sb3_path.name
)
# API endpoint
@app.route('/process_pdf', methods=['POST'])
def process_pdf():
try:
logger.info("Received request to process PDF.")
if 'pdf_file' not in request.files:
logger.warning("No PDF file found in request.")
return jsonify({"error": "Missing PDF file in form-data with key 'pdf_file'"}), 400
pdf_file = request.files['pdf_file']
if pdf_file.filename == '':
return jsonify({"error": "Empty filename"}), 400
# ================================================= #
# Generate Random UUID for project folder name #
# ================================================= #
project_id = str(uuid.uuid4()).replace('-', '')
# project_folder = os.path.join("outputs", f"{project_id}")
project_folder = OUTPUT_DIR / project_id
# =========================================================================== #
# Create empty json in project_{random_id} folder #
# =========================================================================== #
#os.makedirs(project_folder, exist_ok=True)
# Save the uploaded PDF temporarily
filename = secure_filename(pdf_file.filename)
temp_dir = tempfile.mkdtemp()
saved_pdf_path = os.path.join(temp_dir, filename)
pdf_file.save(saved_pdf_path)
# logger.info(f"Created project folder: {project_folder}")
logger.info(f"Saved uploaded PDF to: {saved_pdf_path}")
# Extract & process
# output_path, result = extract_images_from_pdf(saved_pdf_path, json_path)
output_path, result = extract_images_from_pdf(saved_pdf_path)
print(" --------------------------------------- zip_path_str ---------------------------------------", output_path, result)
# Check extracted_sprites.json for "scratch block" in any 'name'
# extracted_dir = os.path.join(JSON_DIR, os.path.splitext(filename)[0])
# extracted_sprites_json = os.path.join(extracted_dir, "extracted_sprites.json")
# if not os.path.exists(extracted_sprites_json):
# return jsonify({"error": "No extracted_sprites.json found"}), 500
# with open(extracted_sprites_json, 'r') as f:
# sprite_data = json.load(f)
project_output = similarity_matching(output_path, project_folder)
logger.info("Received request to process PDF.")
with open(project_output, 'r') as f:
project_skeleton = json.load(f)
images = convert_from_path(saved_pdf_path, dpi=300)
print(type)
page = images[0]
# img_base64 = base64.b64encode(images).decode("utf-8")
buf = BytesIO()
page.save(buf, format="PNG")
img_bytes = buf.getvalue()
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
#image_paths = await convert_pdf_to_images_async(saved_pdf_path)
#updating logic here [Dev Patel]
initial_state_dict = {
"project_json": project_skeleton,
"description": "The pseudo code for the script",
"project_id": project_id,
"project_image": img_b64,
"action_plan": {},
"pseudo_code": {},
"temporary_node": {},
}
final_state_dict = app_graph.invoke(initial_state_dict) # Pass dictionary
final_project_json = final_state_dict['project_json'] # Access as dict
#final_project_json = project_skeleton
# Save the *final* filled project JSON, overwriting the skeleton
with open(project_output, "w") as f:
json.dump(final_project_json, f, indent=2)
logger.info(f"Final project JSON saved to {project_output}")
# --- Call the new function to create the .sb3 file ---
sb3_file_path = create_sb3_archive(project_folder, project_id)
if sb3_file_path:
logger.info(f"Successfully created SB3 file: {sb3_file_path}")
# Instead of returning the local path, return a URL to the download endpoint
download_url = f"https:/webashalarforml-scratch-vlm-v1-2.hf.space/download_sb3/{project_id}"
print(f"DOWNLOAD_URL: {download_url}")
# return jsonify({"message": "Procesed PDF and Game sb3 generated successfully", "project_id": project_id, "download_url": download_url})
return jsonify({
"message": "✅ PDF processed successfully",
"output_json": "output_path",
"sprites": "result",
"project_output_json": "project_output",
"test_url": download_url
})
else:
return jsonify(error="Failed to create SB3 archive"), 500
except Exception as e:
logger.error(f"Error during processing the pdf workflow for project ID {project_id}: {e}", exc_info=True)
return jsonify({"error": f"❌ Failed to process PDF: {str(e)}"}), 500
if __name__ == '__main__':
# os.makedirs("outputs", exist_ok=True) #== commented by P
app.run(host='0.0.0.0', port=7860, debug=True)