AI Automation in 7 Days: Replacing Repetitive Screenshot Workflows

    This article walks through a seven-day effort to automate a repetitive screenshot-and-analysis workflow using general-purpose LLMs as code-generation backends. It breaks the pipeline into seven stages, then documents three major failure modes—delegating the whole flow to a conversational model, relying on general-purpose vision models for chart-to-number extraction, and expecting verbal corrections to stick—along with the engineering fixes for each: explicit state machines with observable atomic steps, a local OpenCV color-mask pipeline, and externalized rules with test-first regression cases. It closes with four production requirements (observability, idempotency, human review, credentials and compliance) and three transferable lessons about determinism, turning corrections into assets, and pricing per stage.

    1. The Problem: Time Lost to Mechanical Work

    Anyone doing data trend analysis knows the trap: log into several designated sites every day, run the same filtered searches, capture three hundred-plus trend charts, read each one, annotate the values, apply a fixed algorithm, and roll everything into a summary table. The work is not technically demanding, but it demands intense focus and perfect repetition. Half a day disappears, your eyes ache, your attention frays, and there is no gap even for a break.

    The defining trait of this kind of task is: the process is fixed, the inputs are fixed, the outputs are fixed, and the only real variable is execution stability. That is exactly where automation fits best. I had previously combined an old laptop with a “trend discovery + AI coding assistant” setup to build a content-topic radar, which proved the path of “describe the requirement in natural language → the tool generates runnable code → run it on a schedule.” So the question followed naturally: if trend scraping can be automated, why not screenshot reading?

    Over the following seven-day break I iterated on that goal, cycling through six different general-purpose LLMs as the code-generation backend, until the full pipeline ran end to end. Below is the complete account of the pitfalls and the engineering fixes that resolved them.

    2. Breaking Down the Flow: Seven Stages, Seven Kinds of Risk

    The full chain abstracts into seven steps:

    1. Session creation and login
    2. Filtered search and result location
    3. Overview (root chart) capture
    4. Detail (breakdown chart) capture
    5. Mapping images to a numeric matrix
    6. Producing conclusions against an algorithm dictionary
    7. Aggregating and archiving results

    One engineering rule applies: the longer the chain, the more the end-to-end success rate approaches the product of the per-stage success rates. If each of seven stages succeeds 95% of the time on its own, the whole pipeline lands at roughly 70%. So the point of automation is not to make one stage “smarter” but to make every stage “more deterministic,” with validation and fallback between stages.

    3. Pitfall 1: Hand the Flow to a Conversational AI and It Improvises

    My first attempt was to paste the entire requirement into an AI coding tool and have it produce the login script in one shot. The results were predictable: wrong element selectors, search results that did not match; then a captcha or a promotional overlay would appear and the script would wait in place until timeout. The most draining part was “teaching it to close popups”—I corrected it more than fifty times, and every time it found a new way to fail: clicking the wrong close button, or simply closing the entire active tab.

    Root cause: conversational models tend to generate code that looks reasonable, while page structure is a runtime fact the model does not possess. The model also has no sense of failure states, so after an error it just repeats the same strategy.

    Fix: separate “writing code” from “running the flow” completely.

    • Have the tool generate only observable atomic operations: open page, wait for element, click, screenshot, log—each with a unique identifier and a timeout.
    • Introduce an explicit state machine to govern the flow, so any failure routes into a single exception branch instead of continuing forward.
    1. # Illustration: constrain the flow with a state machine to stop the model from improvising
    2. STATES = ["login", "search", "capture_overview",
    3. "capture_detail", "recognize", "compute", "report"]
    4. def run_step(state, ctx, max_retry=3):
    5. for attempt in range(max_retry):
    6. try:
    7. return HANDLERS[state](ctx)
    8. except TransientError as e:
    9. ctx.log(f"{state} failed on attempt {attempt+1}: {e}")
    10. ctx.screenshot(f"err_{state}_{attempt}.png") # always capture evidence on failure
    11. time.sleep(2 ** attempt) # exponential backoff
    12. raise FatalError(f"{state} failed repeatedly; aborting and alerting")

    Three hard rules back this up: popups use a “generic close policy” (match the close control by role and text characteristics first; if nothing matches, restart the session rather than guessing coordinates); all waits become explicit condition waits instead of fixed sleeps; and every failure forces a screenshot, preserving the “scene” for the next round of analysis.

    4. Pitfall 2: Trusting a General-Purpose Vision LLM—Costs Rise, Accuracy Stays Low

    Step 5, “image to numeric matrix,” is the core of the whole pipeline. I initially bet everything on general-purpose vision-language model APIs and went through the full trial-and-error curve:

    • Entry-level free model: misread even basic colors, matrix almost entirely wrong;
    • Mid-tier model: broadly usable but clearly prone to hallucination, reading 5 as 3, red as blue;
    • High-tier model: accuracy met the bar, but per-image cost climbed to tens of cents, so three hundred images a day meant tens of dollars daily—a monthly cost that was simply unacceptable.

    Root cause: a trend chart is a highly structured, low-semantics image—limited colors, fixed legends, known axis rules. Using a general semantic model for work that deterministic algorithms should do means paying a high cost to solve a low-entropy problem.

    Fix: switch to a local image-processing pipeline—no network, no token spend.

    1. # Illustration: color masking + contour detection + coordinate back-calculation
    2. import cv2, numpy as np
    3. def extract_series(img_path, palette, axis_origin, axis_scale):
    4. img = cv2.imread(img_path)
    5. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    6. series = {}
    7. for name, hsv_range in palette.items():
    8. mask = cv2.inRange(hsv, *hsv_range)
    9. mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
    10. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    11. if not contours:
    12. series[name] = [] # record missing data explicitly instead of leaving it blank
    13. continue
    14. pts = max(contours, key=cv2.contourArea)[:, 0, :]
    15. series[name] = (pts[:, 0] - axis_origin[0]) / axis_scale[0] # pixels to values
    16. return series

    Four engineering points matter here: use HSV rather than RGB to avoid bias from lighting and compression; apply a morphological close operation first to bridge broken lines; extract the “pixel coordinate → business value” conversion parameters into configuration; and run three self-checks on the recognition output—monotonicity, range, and missing rate—routing anomalous images to a manual review queue. After the change, recognition accuracy held at a usable level and the marginal cost dropped to zero.

    5. Pitfall 3: Assuming “Tell It Once and It Remembers,” and Getting Stuck in a Loop

    The most exhausting part was not the technology but the training process. My expectation was that feeding errors back to the model would make it avoid them next time. Instead I landed in a closed loop: make a mistake → correct it → it complies temporarily → it repeats the mistake a few rounds later → correct it again. Communities often call this in-context circling “triangle collapse.”

    Root cause: session context is volatile, and the model has no durable constraint against approaches that were already rejected; meanwhile, error feedback arrives as natural language mixed into the conversation, so it cannot be enforced.

    Fix: move knowledge out of the conversation and into engineering structures.

    • Externalize the rules: write every convention into configuration and code-standard files, injected automatically before each generation round rather than held in conversational memory.
    1. # rules.yaml — injected before every generation round, replacing verbal corrections
    2. selector_policy: prefer_role_and_text
    3. wait_policy: explicit_condition_only
    4. popup_policy: match_close_control_else_restart
    5. output_contract:
    6. matrix_encoding: "row-major, 0.0-1.0 normalized"
    7. missing_value: null # do not substitute 0 or an empty string
    • Tests first: prepare a case set with boundary samples for each stage (popups, captchas, missing images, broken lines, extreme values); validate immediately after generation, and do not advance if validation fails.
    • Lock in regressions: turn every fixed problem into an automated case so fixes accumulate and cannot regress.
    • Slim the context: expose only the information the current stage needs in each round, reducing cross-interference.

    6. Stability and Cost: Four Things to Cover Before Going Live

    A working pipeline is not the same as one that can run unattended for the long term. Four engineering safeguards are still required:

    1. Observability: structured logs recording per-step duration, retry counts, and recognition confidence, plus monitoring and alerting that notifies a person on consecutive failures.
    2. Idempotency and resume-from-checkpoint: record progress keyed by “date + stage,” so a failed rerun neither re-captures screenshots nor double-bills.
    3. A human fallback channel: low-confidence results never pass silently; they enter a review queue, and human corrections feed back into the case set.
    4. Credentials and compliance: keep account passwords in a secrets manager rather than in code; respect the target sites’ terms of use and rate limits, and control concurrency and request pacing.

    If elastic execution is needed, containerize each stage and let a container platform schedule them, archive raw screenshots and result files in object storage, and use a message queue to decouple stages—all generic capability categories, with no need to bind to any particular vendor.

    7. Retrospective: Three Transferable Lessons

    • Determinism first: solve with rules and algorithms whatever can be solved that way; let the model generate code and handle fuzzy semantics, not precise computation.
    • Turn corrections into assets: verbal corrections are forgotten; configurations, test cases, and validations accumulate. The number of fixes should decrease as iteration proceeds, not stay flat.
    • Price per stage: calculate each step’s cost and the cost of its failures first, then decide what runs in the cloud and what runs locally—avoiding the semantic-model premium on structured images.

    What seven days bought was not some magic tool but a methodology of “constrain + validate + accumulate.” The same thinking transfers to plenty of other repetitive scenarios: report reconciliation, log inspection, asset archiving.