⚙️ Automation

Workflow Process Optimizer

Analyze existing workflows and create optimized automation scripts

★★★ Advanced 40 min January 13, 2025

Use Case

Repetitive workflows waste time and introduce errors. Cowork can analyze your documented processes and create automated scripts that streamline operations.

Example Prompt

I have a documented workflow in ~/Workflows/daily_report.md that describes my daily report generation process. Currently it involves:

1. Export data from 3 Google Sheets
2. Download logs from server
3. Process CSVs to extract KPIs
4. Generate charts
5. Compile into Word document
6. Email to stakeholders

Please:
1. Analyze this workflow for automation opportunities
2. Create a single script that automates everything possible
3. Identify steps that still need manual intervention
4. Estimate time savings
5. Create the automation at ~/Scripts/daily_report/

What Cowork Does

  1. Process Analysis: Reads and parses workflow documentation
  2. Automation Assessment: Identifies automatable steps
  3. Script Generation: Creates comprehensive automation
  4. Integration Setup: Connects to required services
  5. Documentation: Provides usage instructions and limitations

Sample Output

# Workflow Analysis: Daily Report Generation

## Current Process (Manual)
| Step | Description | Time | Automatable |
|------|-------------|------|-------------|
| 1 | Export Google Sheets | 10 min | Yes |
| 2 | Download server logs | 5 min | Yes |
| 3 | Process CSVs | 20 min | Yes |
| 4 | Generate charts | 15 min | Yes |
| 5 | Compile document | 20 min | Yes |
| 6 | Email to stakeholders | 5 min | Yes |

**Total Manual Time**: 75 minutes/day
**Estimated Automated Time**: 5 minutes (script runtime)
**Time Savings**: 70 minutes/day (~93%)

## Automation Limitations
- Google Sheets requires API credentials
- Email may need manual review before sending
- Charts may need visual verification
#!/usr/bin/env python3
# daily_report.py - Automated Daily Report Generation

import os
import sys
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from pathlib import Path
import subprocess
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

# Configuration
CONFIG = {
    'output_dir': Path.home() / 'Reports',
    'sheets_ids': [
        '1ABC...', '1DEF...', '1GHI...'
    ],
    'server': 'logs.example.com',
    'recipients': ['team@example.com', 'manager@example.com'],
}

def export_sheets():
    """Export data from Google Sheets"""
    print("Exporting Google Sheets...")
    dfs = []
    for sheet_id in CONFIG['sheets_ids']:
        url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv"
        df = pd.read_csv(url)
        dfs.append(df)
    return dfs

def download_logs():
    """Download logs from server"""
    print("Downloading server logs...")
    today = datetime.now().strftime('%Y-%m-%d')
    log_path = CONFIG['output_dir'] / f'logs_{today}.txt'

    subprocess.run([
        'scp', f"{CONFIG['server']}:/var/log/app/app.log", str(log_path)
    ], check=True)

    return log_path

def process_data(dfs, log_path):
    """Process data and extract KPIs"""
    print("Processing data...")

    # Combine dataframes
    combined = pd.concat(dfs, ignore_index=True)

    # Calculate KPIs
    kpis = {
        'total_users': combined['user_id'].nunique(),
        'total_revenue': combined['revenue'].sum(),
        'avg_order_value': combined['revenue'].mean(),
        'conversion_rate': combined['converted'].mean() * 100,
    }

    # Process logs
    with open(log_path) as f:
        logs = f.read()
        kpis['error_count'] = logs.count('ERROR')
        kpis['warning_count'] = logs.count('WARNING')

    return combined, kpis

def generate_charts(df, kpis):
    """Generate visualization charts"""
    print("Generating charts...")

    fig, axes = plt.subplots(2, 2, figsize=(12, 10))

    # Revenue trend
    df.groupby('date')['revenue'].sum().plot(ax=axes[0,0], title='Daily Revenue')

    # User distribution
    df['segment'].value_counts().plot.pie(ax=axes[0,1], title='User Segments')

    # KPI summary
    kpi_df = pd.DataFrame([kpis])
    kpi_df[['total_revenue', 'avg_order_value']].plot.bar(ax=axes[1,0])
    axes[1,0].set_title('Revenue Metrics')

    # Conversion funnel
    axes[1,1].bar(['Visits', 'Signups', 'Purchases'],
                  [10000, 2500, 500])
    axes[1,1].set_title('Conversion Funnel')

    plt.tight_layout()

    chart_path = CONFIG['output_dir'] / f'charts_{datetime.now():%Y%m%d}.png'
    plt.savefig(chart_path, dpi=150)
    plt.close()

    return chart_path

def compile_report(kpis, chart_path):
    """Compile final report"""
    print("Compiling report...")

    report = f"""# Daily Report
Generated: {datetime.now():%Y-%m-%d %H:%M}

## Key Performance Indicators

| Metric | Value |
|--------|-------|
| Total Users | {kpis['total_users']:,} |
| Total Revenue | ${kpis['total_revenue']:,.2f} |
| Avg Order Value | ${kpis['avg_order_value']:,.2f} |
| Conversion Rate | {kpis['conversion_rate']:.1f}% |

## System Health
- Errors: {kpis['error_count']}
- Warnings: {kpis['warning_count']}

## Charts
See attached visualization.
"""

    report_path = CONFIG['output_dir'] / f'report_{datetime.now():%Y%m%d}.md'
    report_path.write_text(report)

    return report_path

def send_email(report_path, chart_path):
    """Send report via email"""
    print("Sending report...")
    # Email sending logic here
    print(f"Report sent to {len(CONFIG['recipients'])} recipients")

def main():
    print("Starting Daily Report Generation")
    print("=" * 50)

    try:
        dfs = export_sheets()
        log_path = download_logs()
        df, kpis = process_data(dfs, log_path)
        chart_path = generate_charts(df, kpis)
        report_path = compile_report(kpis, chart_path)

        # Ask for review before sending
        print(f"\nReport ready: {report_path}")
        if input("Send email? (y/n): ").lower() == 'y':
            send_email(report_path, chart_path)

        print("\nDaily report complete!")

    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()

Tips

  • Start with documentation of current process
  • Identify bottlenecks and manual steps first
  • Test automation on sample data before production
  • Keep human-in-the-loop for critical decisions
  • Add logging for troubleshooting