Automating a Data Analysis Pipeline: Lessons from 7 Days of Building an Unattended Workflow
This article walks through rebuilding a manual data trend analysis workflow into an unattended pipeline over seven days. It breaks the process into seven stages, then examines three major failure points—simulated login, chart-to-data extraction, and AI assistant behavior—along with their root causes and engineering fixes. You will see how to model login as a state machine, replace general-purpose vision models with deterministic image processing for controlled charts, and externalize assistant constraints into versioned files and regression tests. The article also covers the four pillars of stable, cost-controlled unattended execution and offers cloud deployment suggestions. Readers looking to eliminate repetitive screenshot-and-report work will find a practical, contract-driven approach here.
Introduction: Reclaiming Time Lost to Mechanical Work Through Engineering
Anyone doing data trend analysis is often trapped by an extremely tedious task: logging into a fixed site every day, mechanically capturing more than three hundred trend charts, reading each chart’s direction, annotating values, applying an algorithm dictionary to produce results, and then compiling everything into a summary. By the end of the day, your eyes are sore and your attention is drained, leaving almost no time for actual thinking.
After building a combined setup of a “hotspot radar plus intelligent coding assistant,” a natural idea emerged: if the toolchain can already inspect information sources automatically, why not let it take over the entire “capture, read, calculate, summarize” chain? So I spent seven days converting this chain from manual operation into a pipeline that can run unattended. I hit enough pitfalls along the way to fill an avoidance manual. This article reviews the whole process using a structure of “symptom, root cause analysis, engineering solution.”
1. Map the Pipeline First: Seven Stages and Their Failure Modes
The entire pipeline can be broken into seven steps: session login, conditional search, root chart capture, boot chart capture, image-to-number-matrix conversion, calculation using the algorithm dictionary, and result aggregation.
The most important engineering insight is this: do not use one large, all-encompassing “intelligent script” to cover all seven steps. Instead, define the input, output, validation rules, and failure exit code for each step. If a step’s output does not satisfy its contract, fail immediately and preserve the scene rather than passing dirty data downstream. In the original practice, every crash was essentially caused by missing contract validation.
2. Pitfall One: Simulated Login Is a State Machine, Not a Script
A typical symptom is that element locator drift leads to incorrect search results, or the script spins in place when it encounters pop-ups or CAPTCHAs. Repeatedly teaching the intelligent coding tool to “close the pop-up first” only results in it sometimes clicking the wrong button and sometimes closing the entire page.
There are three root causes. First, the page is treated as a static structure, ignoring dynamic rendering and asynchronous loading. Second, there is no explicit state machine, so the script does not know “which step it is currently in.” Third, exception handling is missing, so after a failure there is no retry and no scene preservation.
The reliable approach is explicit modeling:
# Pseudocode: login state machine + idempotent retrySTATES = ["open", "auth", "search", "captcha", "done"]def login(ctx, max_retry=3):for i in range(max_retry):try:ctx.goto(ENTRY_URL)ctx.wait_ready() # wait for key elements, not a fixed sleepdismiss_overlays(ctx) # close only the overlay, not the main pageif ctx.need_captcha():raise NeedHuman() # hand off to a human/captcha service, don't force itctx.submit_credentials()assert ctx.is_logged_in() # contract validationreturn "done"except Exception as e:ctx.snapshot(f"login_fail_{i}.png") # preserve the scenelog.error(e)raise RuntimeError("login failed")
Three supporting rules apply: wait for conditions rather than time; overlay dismissal must be scoped to specific selectors; CAPTCHAs belong to a branch that “requires external capability,” so do not expect a general-purpose model to reliably solve them.
3. Pitfall Two: Don’t Overtrust General-Purpose Vision Model APIs for Chart Reading
The most expensive and discouraging stage is “converting screenshots into a number matrix.” Trying models in the order of “free lightweight model, mid-tier model, flagship model” leads through three phases: getting colors wrong; confusing visually similar digits (5 versus 3, red versus blue); and finally reaching acceptable accuracy but losing control of the monthly bill once the per-image cost is multiplied by three hundred images.
The conclusion is clear: when charts are controlled renders (fixed legends, fixed color palettes, fixed axis scales), general-purpose visual recognition is overkill and unstable. A better solution is to downgrade the problem to deterministic image processing:
# Concept sketch: color masking + morphology + linear pixel-to-value mappingimport cv2, numpy as npdef extract_series(img_path, palette, axis):img = cv2.imread(img_path)hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)series = []for name, hsv_range in palette.items():mask = cv2.inRange(hsv, *hsv_range)mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3,3), np.uint8))for x in range(axis.x0, axis.x1):ys = np.where(mask[:, x] > 0)[0]if len(ys):series.append((name, x, axis.to_value(ys.mean())))return series
Key engineering points: calibrate the color palette and axis mapping (the linear relationship between pixels and values) once, and write the calibration parameters into a configuration file rather than hardcoding them; validate each series for monotonicity, range, and missing rate; run offline without consuming tokens, keeping accuracy stable near 100% at zero marginal cost. If truly uncontrolled charts exist, introduce a vision model as a fallback and call it only on low-confidence samples.
4. Pitfall Three: Breaking the “Triangle of Doom”—Don’t Let the AI Assistant Learn from Memory
The most frustrating issue is the correction loop: it makes a mistake, you correct it, it says it will remember, and a few days later it repeats the mistake. This is the inevitable result of placing “long-term constraints” in the conversation context; as the context grows, early agreements get diluted.
The correct approach is to externalize constraints as versionable engineering assets:
- Constraint file: maintain an
AGENTS.mdin the project root that specifies the tech stack, directory conventions, prohibited actions, and a pre-commit checklist; - Regression cases: add an automated test for every historical bug so that “repeating it” turns the CI stage red;
- Small commits: change only one thing at a time to make rollback and diagnosis easier;
- Preserve evidence on failure: archive logs, screenshots, and intermediate artifacts to object storage for later review.
# Local gate before committingpytest -q tests/regress && python tools/lint_contract.py
Once “memory” moves from the model context to files and tests, the forgetting problem becomes an engineering problem.
5. Stability and Cost: Four Pillars of Unattended Operation
- Idempotency and resumability: persist each step’s output with a hash, and reruns only fill in missing shards;
- Concurrency and rate limiting: use a task queue plus a token bucket to avoid being throttled by the target site;
- Observability: feed structured logs and key metrics (success rate, per-step latency, alerts) into a monitoring and alerting system;
- Elasticity and hosting: run stateless executors on a container platform, store artifacts in object storage, use a message queue for peak shaving, and manage credentials through a key management service—never write them into code.
If data volume keeps growing, heavy work can be offloaded to batch processing and parallel computing, and scheduling can be handled by a managed task service, enabling linear scaling without adding headcount.
6. Deployment Suggestions from a Baidu AI Cloud Perspective
The architecture described above is vendor-neutral and represents general engineering practice. If running on Baidu AI Cloud, you can use a container platform to host executors, object storage to archive screenshots and results, a message queue for task distribution, log and monitoring services for observability, and a key management service for unified credentials. The vision fallback stage can be called on demand for low-confidence samples, avoiding the cost overrun caused by full-volume calls.
Conclusion
Seven days yielded only three core principles: treat page interaction as a state machine, downgrade controlled chart recognition to image processing, and externalize the AI assistant’s “memory” into constraint files and regression tests. With these three points in place, the daily grind of three hundred screenshots becomes an unattended pipeline, and people only need to handle exception branches and the evolution of the algorithm dictionary itself.
