pywayne-tools
Utility toolkit for pywayne.tools. Use when tasks need colored console output and tables (wayne_print, wayne_print_table), timing/profiling (@func_timer, @func_timer_batch), YAML config I/O (read_yaml_config, write_yaml_config), logging (wayne_logger), tracing (@trace_calls), retries (@retry), disk caching (@disk_cache), parallel execution (parallel_map), progress bars (@with_progress, progress_iter), file listing/line counting, FileWatcher callbacks, singleton/compose helpers, matplotlib helpers (@maximize_figure, binding_press_release), numpy/pandas display control, or TTS/speech helpers (say, leader_speech). Prefer these built-ins over adding new dependencies or using raw print/logging/config code.
What this skill does
# Pywayne Tools - Comprehensive Utility Toolkit
## Decorators
### Performance Analysis Decorators
#### @func_timer - Single Function Timing
Measure execution time of a single function for quick performance analysis.
```python
from pywayne.tools import func_timer
import time
@func_timer
def compute():
time.sleep(1)
return "done"
compute() # Output: compute excuted in 1.001 s
```
#### @func_timer_batch - Batch Function Timing Statistics
Track number of calls and total execution time, ideal for performance analysis in loops.
```python
from pywayne.tools import func_timer_batch
@func_timer_batch
def process_data(data):
return data * 2
for i in range(100):
process_data(i)
# Access statistics
print(f"Calls: {process_data.num_calls}")
print(f"Total time: {process_data.elapsed_time:.3f}s")
print(f"Average time: {process_data.elapsed_time/process_data.num_calls:.3f}s")
```
#### @trace_calls - Function Call Tracing
Trace detailed information about function calls including caller, arguments, return values, execution time, etc.
```python
from pywayne.tools import trace_calls
# Use default wayne_print output (green)
@trace_calls
def add(x, y):
return x + y
# Use pprint formatted output
@trace_calls(print_type='pprint')
def process(data):
return data
result = add(3, 5)
# Output includes: caller, callee, timestamp, execution time, call count, arguments, return value, file, line number
```
### Visualization Decorators
#### @maximize_figure - Maximize matplotlib Window
Automatically maximize matplotlib figure window, supports multiple backends (TkAgg, wxAgg, Qt4Agg, Qt5Agg, GTK3).
```python
from pywayne.tools import maximize_figure
import matplotlib.pyplot as plt
@maximize_figure
def plot_results(results):
plt.plot(results)
plt.title("Analysis Results")
plt.show()
plot_results([1, 4, 9, 16, 25])
```
#### @binding_press_release - Bind Mouse and Keyboard Events
Bind keyboard and mouse event handlers to matplotlib figures.
```python
from pywayne.tools import binding_press_release
import matplotlib.pyplot as plt
def on_button_press(event):
print(f"Mouse pressed: x={event.x}, y={event.y}")
def on_key_press(event):
print(f"Key pressed: {event.key}")
func_dict = {
'button_press_event': on_button_press,
'key_press_event': on_key_press,
}
@binding_press_release(func_dict)
def interactive_plot():
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
plt.show()
return fig
interactive_plot()
```
### Design Pattern Decorators
#### @singleton - Singleton Pattern
Ensure a class has only one instance, thread-safe implementation.
```python
from pywayne.tools import singleton
@singleton
class ConfigManager:
def __init__(self):
self.config = {}
def set(self, key, value):
self.config[key] = value
c1 = ConfigManager()
c2 = ConfigManager()
assert c1 is c2 # True
c1.set("debug", True)
print(c2.config) # {'debug': True}
```
### Retry and Caching Decorators
#### @retry - Automatic Retry with Exponential Backoff
Automatically retry failed functions with exponential backoff strategy.
```python
from pywayne.tools import retry
import random
# Basic usage
@retry(max_tries=3, delay=1.0, backoff=2.0)
def unreliable_request():
if random.random() < 0.7:
raise IOError("Network error")
return "Success"
# Specify exception types to catch
@retry(
max_tries=5,
delay=0.5,
backoff=2.0,
exceptions=(IOError, TimeoutError)
)
def upload_file(path):
# Simulate upload operation
pass
# Custom retry callback
def on_retry_callback(exc, attempt):
print(f"Retry attempt {attempt}, reason: {exc}")
@retry(max_tries=3, on_retry=on_retry_callback)
def flaky_operation():
pass
result = unreliable_request()
```
**Use Cases**: Handle intermittent failures when calling Lark API, Aliyun OSS, LLM APIs, dealing with timeouts or rate limits.
**Parameters**:
- `max_tries`: Maximum number of attempts (including first call)
- `delay`: Initial delay in seconds before first retry
- `backoff`: Multiplier for delay after each retry (exponential backoff)
- `exceptions`: Tuple of exception types that trigger retry
- `on_retry`: Optional callback `(exception, attempt) -> None` called before each retry
#### @disk_cache - Disk Cache with Persistence
Pickle-based disk cache with TTL support, persists across process restarts.
```python
from pywayne.tools import disk_cache
import time
# Cache for 1 hour
@disk_cache(ttl=3600)
def expensive_query(url):
time.sleep(2) # Simulate expensive operation
return f"Result from {url}"
# First call: takes 2 seconds
result1 = expensive_query("https://api.example.com")
# Second call: instant return (from cache)
result2 = expensive_query("https://api.example.com")
# Never-expire cache
@disk_cache()
def compute_hash(data):
return hash(data)
# Ignore certain parameters (don't affect cache key)
@disk_cache(ttl=300, ignore_kwargs=['verbose'])
def process(data, verbose=False):
return data * 2
# Manually clear cache
compute_hash.cache_clear()
# Check cache directory
print(compute_hash.cache_dir) # ~/.wayne_cache
```
**Use Cases**: Cache LLM inference results, slow queries, large file parsing to avoid redundant computation.
**Parameters**:
- `ttl`: Cache validity period in seconds, `None` means never expire
- `cache_dir`: Custom cache directory, defaults to `~/.wayne_cache`
- `ignore_kwargs`: List of keyword argument names to ignore when computing cache key
**Additional Attributes**:
- `func.cache_clear()`: Clear all cache files for this function
- `func.cache_dir`: Cache directory path string
### Progress Display Decorators
#### @with_progress - Auto-add Progress Bar
Automatically wrap the first iterable argument of decorated function with tqdm progress bar.
```python
from pywayne.tools import with_progress
@with_progress(desc="Processing images")
def process_images(image_list):
for img in image_list: # image_list is automatically wrapped with tqdm
# Process image
pass
# Specify unit and total
@with_progress(desc="Downloading files", unit="file", total=100)
def download_batch(urls):
for url in urls:
# Download file
pass
process_images(["img1.jpg", "img2.jpg", "img3.jpg"])
```
**Use Cases**: Automatically show progress bar when looping inside functions without modifying loop code.
## File Operations
### list_all_files - Recursive File Listing with Filtering
Recursively traverse directories and filter files by keyword conditions.
```python
from pywayne.tools import list_all_files
# Must contain ".txt"
files = list_all_files("./data", keys_and=[".txt"], full_path=True)
# Result: ['./data/log.txt', './data/sub/notes.txt']
# At least one keyword (OR logic)
files = list_all_files("./src", keys_or=[".py", ".json"])
# Matches: config.json, main.py
# Must contain all keywords (AND logic)
files = list_all_files("./logs", keys_and=["2024", ".log"])
# Matches: 2024-01-15.log, 2024-02-20.log
# Exclude specific keywords
files = list_all_files("./", outliers=["__pycache__", ".git", "node_modules"])
# Combined usage
files = list_all_files(
"./project",
keys_and=[".py"], # Must be Python files
keys_or=["test", "main"], # Contains test or main
outliers=["__pycache__"], # Exclude cache directories
full_path=True # Return absolute paths
)
```
**Parameters**:
- `root`: Root directory path
- `keys_and`: List of keywords that must all be present (AND logic)
- `keys_or`: List of keywords where at least one must be present (OR logic)
- `outliers`: Exclude files containing these keywords
- `full_path`: Whether to return absolute paths (default False)
**Use Cases**: Batch file processing, log collection, project file analysis.
### count_file_lines - Fast File Line Counting
Efficiently count lines in large files using block reading.
```python
from pywayne.tools import count_file_lines
num_lines = count_file_lines("lRelated in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.