The Automation Showdown: AI Workflow vs. Python Script
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 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
- The Traditional Script (The Craftsman): A hand-written Python function optimized for a specific task. It's reliable and fast, but rigid. If the task changes, a developer must rewrite the code.
- The Hyperautomation AI (The Adaptable Generalist): This method simulates modern Robotic Process Automation (RPA). You give it a high-level goal, and an agentic AI generates the logic on the fly. It's flexible and empowers "citizen developers," but introduces variability.
How to Run the Showdown
- Prerequisites: You need Python 3, pip, and an API key from an LLM provider like OpenAI.
- Save the Script: Click "Copy Script" below and save the code as `automation_showdown.py`.
- Install Dependencies: In your terminal, run:
pip install openai python-dotenv - Configure API Key: Create a `.env` file and add your key:
OPENAI_API_KEY='your_secret_key' - Create Sample Data: Create an `invoices` folder. Inside, create two files: `invoice_1.txt` (with `Total Amount: $150.75`) and `invoice_2.txt` (with `total of 2,300.50 USD`).
- Execute the Script: Run from your terminal:
python automation_showdown.py - Analyze the Output: Compare the accuracy and speed of each method.
The Verdict: When to Use Each Approach
After running the script, you'll see the core trade-off:
- The hand-written script is faster and 100% predictable for the format it was designed for, but completely fails on the slightly different format of the second invoice.
- The AI-generated workflow is slower but successfully adapts and parses both invoice formats because it understands the *intent* of the request, not just a rigid pattern.
The future is 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
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"
def traditional_invoice_parser(text):
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
def ai_workflow_generator(text, goal):
system_message = (
"You are a data extraction AI. Analyze the user's text to find the information "
"requested in their goal. Return ONLY a JSON object with the keys "
"'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
try:
return eval(response_str)
except:
return {"error": "Failed to parse LLM response"}
def main():
print("\n--- Hyperautomation vs. Python Scripts: A Showdown ---")
invoice_folder = "invoices"
if not os.path.isdir(invoice_folder):
print(f"\nError: The '{invoice_folder}' folder was not found.")
return
files_to_process = [f for f in os.listdir(invoice_folder) if f.endswith('.txt')]
if not files_to_process:
print(f"\nError: No .txt files found in the '{invoice_folder}' folder.")
return
natural_language_goal = "Extract the invoice number, date, and total amount."
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()
print("\n\033[1;93m1. Running Traditional 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")
print("\n\033[1;95m2. Running AI-Generated 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")
if __name__ == "__main__":
main()