Python Script

Hyperautomation vs. Python Scripts: A Practical Showdown for 2025

In the world of automation, a crucial debate is unfolding: should you use a meticulously hand-crafted Python script or embrace the power of Hyperautomation and AI-driven platforms? One promises precision and control, the other speed and adaptability. This guide doesn't just discuss the theory—it provides a hands-on Python framework to put them to the test.

We'll explore a practical showdown where a traditional script competes against an AI-generated workflow to perform a real-world task. This is your definitive guide to understanding the trade-offs between classic code and the new era of intelligent automation.

The Contenders: Two Philosophies of Automation

How to Run the Showdown:

  1. Prerequisites: You need Python 3 and pip installed. You will also need an API key from an LLM provider like OpenAI.
  2. Save the Script: Click the "Copy Script" button below and save the code into a file named `automation_showdown.py`.
  3. Install Dependencies: Open your terminal and run the command: pip install openai python-dotenv
  4. Configure API Key: In the same folder, create a new file named `.env`. Inside this file, add your API key like this: OPENAI_API_KEY='your_secret_key'
  5. Create Sample Data: For our test, we'll process invoices. Create a folder named `invoices` in the same directory. Inside it, create two text files:
    • invoice_1.txt with the content: `Invoice Number: INV-101, Date: 2025-07-20, Total Amount: $150.75`
    • invoice_2.txt with the content: `Order #ORD-202 from 2025-07-21 for a total of 2,300.50 USD`
  6. Execute the Script: Run the script from your terminal: python automation_showdown.py
  7. Analyze the Output: The script will run both methods and print the structured data they extracted. You can compare their accuracy, speed, and how they handled different text formats.

The Verdict: When to Use Each Approach

After running the script, you'll see the core trade-off:

The future of the digital workforce isn't about choosing one over the other. It's about a hybrid automation model where developers build robust frameworks and AI agents handle the dynamic, ever-changing tasks within them. This script is your first step into that exciting future.


import os
import re
import time
from openai import OpenAI
from dotenv import load_dotenv

# --- Configuration ---
load_dotenv()
API_KEY = os.getenv("OPENAI_API_KEY")
if not API_KEY:
    raise ValueError("OpenAI API key not found. Please create a .env file.")
client = OpenAI(api_key=API_KEY)
MODEL = "gpt-4o"

# --- Method 1: The Traditional, Hand-Written Script ---
def traditional_invoice_parser(text):
    """
    A rigid, hand-written parser using regular expressions.
    It expects a specific format.
    """
    patterns = {
        'invoice_number': r"Invoice Number: (INV-\d+)",
        'date': r"Date: (\d{4}-\d{2}-\d{2})",
        'total_amount': r"Total Amount: \$([\d,]+\.\d{2})"
    }
    
    extracted_data = {}
    for key, pattern in patterns.items():
        match = re.search(pattern, text)
        extracted_data[key] = match.group(1) if match else None
        
    return extracted_data

# --- Method 2: The Hyperautomation / Agentic AI Approach ---
def ai_workflow_generator(text, goal):
    """
    Simulates a Hyperautomation platform by using an LLM to generate
    the parsing logic based on a natural language goal.
    """
    system_message = (
        "You are an expert data extraction AI. Your task is to analyze the user's text "
        "and extract the specific information requested in their goal. "
        "Return ONLY a JSON object with the extracted data. The keys should be 'invoice_number', 'date', and 'total_amount'."
    )
    
    prompt = f"Goal: {goal}\n\nText to analyze:\n---\n{text}\n---"
    
    response_str = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": system_message},
            {"role": "user", "content": prompt},
        ],
        temperature=0.2,
    ).choices[0].message.content
    
    # The LLM should return a valid JSON string, which we can parse
    try:
        return eval(response_str) # Using eval is simple for this demo, json.loads is safer in production
    except:
        return {"error": "Failed to parse LLM response"}

# --- The Showdown Orchestrator ---
def main():
    print("\n--- Hyperautomation vs. Python Scripts: A Showdown ---")
    
    invoice_folder = "invoices"
    if not os.path.isdir(invoice_folder):
        print(f"\n\033[91mError:\033[0m The '{invoice_folder}' folder was not found.")
        print("Please create it and add sample .txt files as per the instructions.")
        return

    files_to_process = [f for f in os.listdir(invoice_folder) if f.endswith('.txt')]
    if not files_to_process:
        print(f"\n\033[91mError:\033[0m No .txt files found in the '{invoice_folder}' folder.")
        return

    natural_language_goal = "Extract the invoice number, date, and total amount from the text."
    
    for filename in files_to_process:
        print(f"\n\n\033[1;96m--- Processing: {filename} ---\033[0m")
        filepath = os.path.join(invoice_folder, filename)
        with open(filepath, 'r') as f:
            content = f.read()

        # --- Run Traditional Script ---
        print("\n\033[1;93m1. Running Traditional Hand-Written Script...\033[0m")
        start_time = time.time()
        traditional_result = traditional_invoice_parser(content)
        end_time = time.time()
        print(f"  Result: {traditional_result}")
        print(f"  Time Taken: {end_time - start_time:.4f} seconds")

        # --- Run AI-Generated Workflow ---
        print("\n\033[1;95m2. Running AI-Generated Hyperautomation Workflow...\033[0m")
        start_time = time.time()
        ai_result = ai_workflow_generator(content, natural_language_goal)
        end_time = time.time()
        print(f"  Result: {ai_result}")
        print(f"  Time Taken: {end_time - start_time:.4f} seconds")

    print("\n\n\033[1;96m--- Showdown Complete ---\033[0m")
    print("Notice how the traditional script is faster but fails on unstructured formats,")
    print("while the AI workflow is slower but more flexible and resilient to change.")

if __name__ == "__main__":
    main()