Basic Usage

Python Code Runner blocks allow you to execute Python scripts within your Hunch canvas. This powerful feature enables you to process data, interact with external services, and create dynamic outputs.

Simple Example

Let’s start with a basic example. Assume we have a canvas with two input content blocks:

  1. A block titled “First Name”
  2. A block titled “Last Name”

We’ll create a Python Code Runner block that combines these inputs to greet the person.

import hunch

# Get the contents of the input blocks
first_name = hunch.block(title="First Name").output
last_name = hunch.block(title="Last Name").output

# Combine the names and create a greeting
greeting = f"Hello {first_name} {last_name}!"

# Output the greeting
hunch.output(greeting)

This script will output: “Hello [First Name] [Last Name]!” where [First Name] and [Last Name] are replaced with the actual contents of those input blocks.

Using the hunch Package

The hunch package is a crucial part of working with Python Code Runner blocks. It provides several useful functions for interacting with your Hunch canvas.

Key Functions

  1. hunch.output()

    • Use this to send output from your script.
    • Example: hunch.output("This will be displayed in the output.")
  2. hunch.block()

    • Retrieves a specific block from your canvas.
    • Example: hunch.block(title="Block Title")
  3. hunch.input()

    • Loads all input data for the Code Runner block.
    • Example: input_data = hunch.input()
  4. hunch.compiled_prompt()

    • Gets the entire compiled prompt from upstream blocks.
    • Example: full_prompt = hunch.compiled_prompt()

Input Handling

Accessing Specific Blocks

To access the content of a specific block, use the hunch.block() function:

import hunch

# Access a block by its exact title
block_content = hunch.block(title="Exact Block Title").output

# Access a block by case-insensitive title
block_content = hunch.block(ititle="block title").output

Working with All Inputs

To work with all input blocks at once:

import hunch

input_data = hunch.input()
for block in input_data.blocks:
    hunch.output(f"Block '{block.title}': {block.output}")

Output Handling

Text Output

Use hunch.output() to send text output:

import hunch

hunch.output("This is a simple text output.")
hunch.output("You can call hunch.output() multiple times.")

File Output

To output files, write them to the /output directory:

import os
from PIL import Image, ImageDraw

def create_smiling_emoji(output_path="/output/smile.png"):
    # Create a new image with a transparent background
    size = (400, 400)
    image = Image.new('RGBA', size, (0, 0, 0, 0))

    # Create a drawing object
    draw = ImageDraw.Draw(image)

    # Draw the yellow face
    draw.ellipse([20, 20, 380, 380], fill=(255, 255, 0))

    # Draw the eyes
    draw.ellipse([120, 120, 160, 160], fill=(0, 0, 0))
    draw.ellipse([240, 120, 280, 160], fill=(0, 0, 0))

    # Draw the smile
    draw.arc([100, 180, 300, 300], start=0, end=180, fill=(0, 0, 0), width=10)

    # Save the image
    image.save(output_path)

if __name__ == "__main__":
    try:
        create_smiling_emoji()
    except Exception as e:
        print(f"Failed to create the smiling emoji: {str(e)}")

Markdown Rendering

Output is rendered as Markdown. You can use Markdown syntax in your output:

import hunch

hunch.output("# This is a Markdown Header")
hunch.output("- List item 1")
hunch.output("- List item 2")
hunch.output("**Bold text** and *italic text*")

Error Handling

Implement try-except blocks to handle potential errors:

import hunch

try:
    # Some code that might raise an exception
    result = some_risky_operation()
    hunch.output(f"Operation successful: {result}")
except Exception as e:
    hunch.output(f"An error occurred: {str(e)}")

Advanced Usage

Working with External Libraries

You can use many standard Python libraries and some additional libraries. Here’s an example using requests:

import hunch
import requests

try:
    response = requests.get("https://api.example.com/data")
    data = response.json()
    hunch.output(f"Received data: {data}")
except requests.RequestException as e:
    hunch.output(f"API request failed: {str(e)}")

Data Transformation

Python is excellent for data transformation. Here’s a simple example:

import hunch
import json

# Assume we have a JSON input block
json_data = hunch.block(title="JSON Input").output

# Parse the JSON
data = json.loads(json_data)

# Transform the data
transformed_data = {k.upper(): v.capitalize() for k, v in data.items()}

# Output the transformed data
hunch.output(json.dumps(transformed_data, indent=2))

Best Practices

  1. Modular Code: Break your code into functions for better readability and reusability.
  2. Error Handling: Always include error handling to make your scripts more robust.
  3. Comments: Add comments to explain complex logic or non-obvious operations.
  4. Input Validation: Validate inputs to ensure your script can handle unexpected data.

Conclusion

Python Code Runner blocks offer a powerful way to extend the capabilities of your Hunch canvas. By combining Python’s versatility with Hunch’s AI-driven workflows, you can create sophisticated, dynamic, and intelligent applications.

Remember to explore the hunch package documentation for more advanced features and always consider security and performance when writing your scripts.