Skip to content

Usage Examples

Eli Lab edited this page Mar 2, 2026 · 2 revisions

Usage Examples

Practical code examples and common patterns.

Table of Contents

  1. Note Generator
  2. Phonetic Analysis
  3. File Operations
  4. UI Components
  5. Integration Examples
  6. Common Patterns

Note Generator

Basic Note Generation

from hiro_ust.generator import NoteGenerator

gen = NoteGenerator(base_length=240, length_var=0.3)

# Calculate note length
length = gen.get_note_length("a", length_factor=1.0)
print(f"Note length: {length} ticks")

# Generate random pitch
pitch = gen.get_random_pitch(
    root_key=72,
    scale_name="Major Pentatonic",
    intone_level="Medium (2)",
    use_motifs=True
)
print(f"Pitch: {pitch} MIDI")

# Create stretched notes
stretches = gen.create_stretch_notes("あ", stretch_prob=0.5)
for phoneme, factor in stretches:
    print(f"  {phoneme}: {factor}")

Pitch Bends

from hiro_ust.generator import PitchBendCalculator

# Quartertone pitch bend
pbs, pbw = PitchBendCalculator.calculate_quartertone_bend(60.5)
print(f"PBS: {pbs}, PBW: {pbw}")  # PBS: 0;25, PBW: 10

# Accent-based pitch bend
melody_brain = some_melody_instance
pbs, pbw, pby, pbm = PitchBendCalculator.calculate_accent_bend(
    melody_brain,
    note_length=240,
    accent="Odaka"
)
print(f"PBS: {pbs}, PBW: {pbw}, PBY: {pby}")

Envelope (Intensity)

from hiro_ust.generator import EnvelopeCalculator

intensity = EnvelopeCalculator.calculate_intensity(
    melody_brain=brain,
    intensity_base=80,
    note_position=5,
    phrase_length=12
)
print(f"Intensity: {intensity}")  # 75-85 (adjusted)

Phonetic Analysis

Mora Analysis

from hiro_ust.voice import MoraAnalyzer

# Single mora analysis
mora = "きゃ"
vowel = MoraAnalyzer.get_vowel(mora)              # "a"
consonant = MoraAnalyzer.get_consonant(mora)      # "kya"
mora_type = MoraAnalyzer.classify_mora_type(mora) # "consonant"

print(f"{mora}: vowel={vowel}, consonant={consonant}, type={mora_type}")

# Batch analysis
word = "きゃっきゃ"
for char in word:
    vowel = MoraAnalyzer.get_vowel(char)
    is_voiced = MoraAnalyzer.is_voiced(char)
    print(f"{char}: vowel={vowel}, voiced={is_voiced}")

Accent Patterns

from hiro_ust.voice import AccentAnalyzer

# Atamadaka (first mora high)
high_moras = AccentAnalyzer.get_accent_moras("Atamadaka", 3)
print(f"High moras: {high_moras}")  # [0]

# Check each mora
for pos in range(3):
    is_high = AccentAnalyzer.should_be_high(pos, "Atamadaka", 3)
    print(f"Mora {pos}: high={is_high}")

# Odaka (last mora high)
high_moras = AccentAnalyzer.get_accent_moras("Odaka", 3)
print(f"High moras: {high_moras}")  # [2]

Vowel Properties

from hiro_ust.voice import VowelHarmony

# Analyze vowel characteristics
for char in "あいうえお":
    openness = VowelHarmony.get_vowel_openness(char)
    is_back = VowelHarmony.is_back_vowel(char)
    is_high = VowelHarmony.is_high_vowel(char)
    print(f"{char}: openness={openness}, back={is_back}, high={is_high}")

Text Normalization

from hiro_ust.voice import PhoneticNormalizer

normalizer = PhoneticNormalizer()

# Normalize various formats
text = "あ い う"
clean = normalizer.normalize_whitespace(text)  # "あ い う"

text = "ら−めん"  # Different dash character
clean = normalizer.normalize_choonpu(text)      # "らーめん"

text = "さ  っ  き"
clean = normalizer.normalize_small_tsu_spacing(text)  # "さっき"

File Operations

Save UST File

from hiro_ust.ui import FileDialog, DialogMessages

# Show save dialog
filepath = FileDialog.save_ust(
    parent_widget=root,
    initial_name="Hiro_Main",
    initial_dir=None  # Uses default
)

if filepath:
    try:
        # Generate and save content
        ust_content = "..."  # Your UST content
        with open(filepath, "w", encoding="utf-8-sig") as f:
            f.write(ust_content)
        
        # Show success
        DialogMessages.show_file_saved(filepath, root)
    except Exception as e:
        DialogMessages.show_file_error(filepath, e, root)

Preset Management

from hiro_ust.ui import FileDialog, DialogMessages

# Save preset
preset_path = FileDialog.save_preset(root, "My_Preset")
if preset_path:
    import json
    preset_data = {"tempo": 120, "scale": "Major"}
    with open(preset_path, "w") as f:
        json.dump(preset_data, f)
    DialogMessages.show_info("Saved", "Preset saved!", root)

# Load preset
preset_path = FileDialog.open_preset(root)
if preset_path:
    with open(preset_path, "r") as f:
        preset_data = json.load(f)
    DialogMessages.show_info("Loaded", "Preset loaded!", root)

Format Choice

from hiro_ust.ui import SaveDialog

# Ask user for format
format_choice = SaveDialog.ask_save_format(root)

if format_choice == "ustx":
    filepath = FileDialog.save_ustx(root)
elif format_choice == "ust":
    filepath = FileDialog.save_ust(root)
else:
    return  # Cancelled

UI Components

Parameter Panel

from hiro_ust.ui import ParameterPanel

# Create organized parameter panel
panel = ParameterPanel(root, "Audio Settings")

# Add different control types
panel.add_entry("project", "Project Name:", "Hiro", width=20)
panel.add_spinbox("tempo", "Tempo (BPM):", from_=60, to=240, increment=5)
panel.add_combobox("voice", "Voice:", ["Soprano", "Alto", "Tenor", "Bass"], "Alto")
panel.add_scale("intensity", "Intensity:", from_=50, to=120, initial=80)

panel.pack(fill="both", expand=True, padx=10, pady=10)

# Get all values
config = panel.get_values()
print(config)  # {"project": "Hiro", "tempo": 120, ...}

# Set multiple values
panel.set_values({"tempo": 130, "voice": "Tenor"})

Checkbutton Group

from hiro_ust.ui import CheckbuttonGroup

options = CheckbuttonGroup(root, "Melody Options")

options.add_checkbox("motif", "🎼 Use Motif Memory", default=True)
options.add_checkbox("lyrical", "🎭 Lyrical Mode", default=True)
options.add_checkbox("flat", "🎹 Monotone", default=False)
options.add_checkbox("microtones", "♯ Microtones", default=False)

options.pack(fill="x", padx=10)

# Get all states
states = options.get_all()
print(states)  # {"motif": True, "lyrical": True, "flat": False, ...}

# Update single state
options.set("flat", True)

Progress Bar

from hiro_ust.ui import ProgressBar

progress = ProgressBar(root)
progress.pack(fill="x", padx=10, pady=5)

# Simulate processing
for i in range(101):
    progress.set_label(f"Processing... ({i} notes)")
    progress.set_progress(i)
    root.update()
    # Do some work...

progress.set_label("Complete!")
progress.set_progress(100)

Preset Manager

from hiro_ust.ui import PresetManager

def on_save():
    print("Saving preset...")
    # Your save logic

def on_load():
    print("Loading preset...")
    # Your load logic

preset_mgr = PresetManager(
    root,
    on_save=on_save,
    on_load=on_load
)
preset_mgr.pack(fill="x", padx=10, pady=5)

# Update status
preset_mgr.set_status("✅ Preset: Default.json")

Integration Examples

Complete Note Generation Pipeline

from hiro_ust.generator import NoteGenerator, PitchBendCalculator

def generate_note_params(phoneme, root_key, scale, melody_brain):
    """Generate all parameters for a single note."""
    gen = NoteGenerator(base_length=240, length_var=0.3)
    
    # Generate base parameters
    length = gen.get_note_length(phoneme)
    pitch = gen.get_random_pitch(root_key, scale, use_motifs=True)
    
    # Calculate pitch bends
    if pitch != int(pitch):  # Microtone
        pbs, pbw = PitchBendCalculator.calculate_quartertone_bend(pitch)
    else:
        pbs, pbw = "0;0", "0"
    
    return {
        "length": length,
        "pitch": int(pitch),
        "pbs": pbs,
        "pbw": pbw
    }

# Use it
brain = some_melody_brain
for phoneme in phonemes:
    params = generate_note_params(phoneme, 72, "Major", brain)
    print(params)

Text Preprocessing Pipeline

from hiro_ust.voice import (
    PhoneticNormalizer, MoraAnalyzer, AccentAnalyzer
)

def preprocess_lyrics(text, accent_type="None"):
    """Preprocess and analyze lyrics."""
    normalizer = PhoneticNormalizer()
    
    # Clean text
    text = normalizer.normalize_whitespace(text)
    text = normalizer.normalize_choonpu(text)
    
    # Analyze each mora
    moras = []
    for idx, char in enumerate(text):
        mora = {
            "char": char,
            "vowel": MoraAnalyzer.get_vowel(char),
            "type": MoraAnalyzer.classify_mora_type(char),
            "voiced": MoraAnalyzer.is_voiced(char)
        }
        
        # Add accent info if applicable
        if accent_type != "None":
            mora["is_high"] = AccentAnalyzer.should_be_high(
                idx, accent_type, len(text)
            )
        
        moras.append(mora)
    
    return moras

# Use it
moras = preprocess_lyrics("きゃっきゃ", "Odaka")
for mora in moras:
    print(mora)

Complete Save Workflow

from hiro_ust.ui import FileDialog, SaveDialog, DialogMessages

def save_project_with_format(ust_content, root):
    """Complete save workflow with format choice."""
    
    # Ask format
    format_choice = SaveDialog.ask_save_format(root)
    if not format_choice:
        return False  # User cancelled
    
    # Save with correct format
    if format_choice == "ustx":
        filepath = FileDialog.save_ustx(root, "Hiro_Main")
    else:
        filepath = FileDialog.save_ust(root, "Hiro_Main")
    
    if not filepath:
        return False  # User cancelled
    
    # Save content
    try:
        with open(filepath, "w", encoding="utf-8-sig") as f:
            f.write(ust_content)
        
        DialogMessages.show_file_saved(filepath, root)
        return True
    except Exception as e:
        DialogMessages.show_file_error(filepath, e, root)
        return False

# Use it
success = save_project_with_format(ust_content, root)

Common Patterns

Caching Generator Instance

# Instead of creating new generator each time
class MyApp:
    def __init__(self):
        # Create once
        self.note_gen = NoteGenerator()
    
    def generate_note(self, phoneme):
        # Reuse
        return self.note_gen.get_note_length(phoneme)

Batch Processing with Progress

from hiro_ust.ui import ProgressBar

progress = ProgressBar(root)
progress.pack()

phonemes = ["a", "ki", "ya", "ri", "ku"]
for idx, phoneme in enumerate(phonemes):
    progress.set_label(f"Processing {phoneme}...")
    progress.set_progress((idx / len(phonemes)) * 100)
    
    # Process phoneme
    length = note_gen.get_note_length(phoneme)
    
    root.update()  # Update UI

Error Handling

from hiro_ust.ui import DialogMessages

try:
    result = some_operation()
except ValueError as e:
    DialogMessages.show_error("Invalid Input", str(e), root)
except Exception as e:
    DialogMessages.show_error("Error", f"Unexpected error: {e}", root)

More help?User GuideFAQArchitecture

Wiki Navigation

⚠️ Windows Only • Best with OpenUtau

📖 User Guide

🔍 Reference


Need help?FAQ
Ready to use?User Guide

Clone this wiki locally