AI 资讯
From Docker Compose to Kubernetes: What Actually Changes
If you're comfortable with docker compose up , you already understand more of Kubernetes than you think. Compose taught you to describe an application declaratively — services, their images, their config, how they talk to each other — instead of running containers by hand. Kubernetes is the same instinct, scaled out across a cluster, with more moving parts because it's solving a harder problem: keeping that application running when machines fail. The good news is the mental model transfers. The honest news is that the operational surface grows, and it's worth knowing exactly what changes before you commit. Let me map the concepts you already know onto their Kubernetes equivalents, show the YAML side by side, and be straight about the parts that get harder. First, the thing that doesn't change: your images This trips people up, so let's clear it early. The Docker images you already build run on Kubernetes unmodified. Kubernetes doesn't use the Docker daemon to run them — most clusters use containerd or CRI-O — but every one of those runtimes runs standard OCI images. That's the whole point of the OCI standard: the image you built with docker build is the same artifact the cluster pulls and runs. docker build -t registry.example.com/myapp:1.4.2 . docker push registry.example.com/myapp:1.4.2 That image works identically whether docker run starts it or a Kubernetes node's containerd does. So the packaging is settled. What changes is everything around the container. The concept map Here's the translation table I'd keep next to you while you learn: Docker Compose Kubernetes What changed service Deployment + Service Running vs. reachable are now two objects image: spec.containers[].image Same OCI image ports: Service (+ Ingress for external) Networking is explicit and named depends_on: probes / initContainers Ordering becomes health, not sequence environment: / .env ConfigMap / Secret Config decoupled from the pod volumes: PersistentVolume / PVC Storage is claimed, not jus
AI 资讯
Docker Containerization: Turning 'Works on My Machine' Into a Reproducible Artifact
"Works on my machine" is one of the oldest jokes in software, and it stopped being funny the first time it cost me a weekend. The code was fine. The environment wasn't. A library version on the build box didn't match production, and nobody could see it because "the environment" was a fuzzy, undocumented thing that lived partly in a config management tool, partly in someone's .bashrc , and partly in tribal memory. Containerization is the boring, durable fix for that whole class of problem. Not because containers are magic, but because they force you to turn a fuzzy environment into a single, inspectable, reproducible artifact. That shift — from "a machine we hope is configured right" to "an image we can point at" — is the actual win. Let me walk through what that means operationally, with a minimal example. What containerization actually solves Strip away the tooling and a container image is one thing: your application plus everything it needs to run, packaged together and frozen. The OS libraries, the runtime, the dependencies, your code — all captured at build time into one immutable blob with a content-addressable identity. That has three consequences that matter when you're the one on call: The environment stops being a variable. If it runs from image myapp:1.4.2 in staging, the same image runs in production. You're no longer debugging the difference between two machines. The artifact is immutable. You don't patch a running container in place and hope. You build a new image, tag it, and roll it out. The old one still exists, unchanged, if you need to go back. Rollback becomes trivial. "Roll back" means "run the previous image tag." That's it. No reinstalling packages, no un-applying config drift. After enough years in operations, you learn that most 3 a.m. incidents aren't exotic. They're some version of "this box isn't like the other boxes." Containers don't make you smarter, but they take that entire category off the table. Images vs. containers, briefly These
AI 资讯
Reclaim free space from VirtualBox VM on Windows host
When you delete files in your virtualbox VM in order to free up space on the host filesystem, this space is not automatically reclaimed. In order for the host system to see the changes you need to rewrite the free space with zeroes. Follow the below steps to perform this operation: Install zerofree package. It is needed to rewrite the free space with zeroes. Mount the filesystem as "readonly". This is needed for the tool to be able to perform it's task. If you're working with the "/", easiest way to mount it as readonly is to edit the kernel parameters. Edit /etc/default/grub . Find the GRUB_CMDLINE_LINUX_DEFAULT line. Add init=/bin/bash to it reboot Run zerofree -v /dev/sdX . This could run for some time, depending on the size of your disk. After it's done, run exec init to finish booting up. Shutdown the VM in order to be able to run the next command which requires a lock on the VDI volume. On the Windows host run VBoxManage.exe modifymedium "path\to\disk.vdi" --compact
AI 资讯
Why We're Stuck With GPUs This Long?
I'm probably not the only one who checks every few months whether a GPU alternative has finally shipped, mostly so I can cancel a few subscriptions. Nobody doubts it's physically possible or that people have tried. The real question is why it hasn't actually happened, and the answer is economic and structural, not technical. GPUs are not uniquely ideal. They're uniquely general LLM workloads are dense matmul, high parallelism, memory-bandwidth-bound compute. GPUs handle this well but weren't built for it specifically. An ASIC purpose-built for transformer inference should beat a GPU on perf-per-watt and perf-per-dollar, and in narrow slices, it already does: Groq's LPU beats GPUs on single-stream inference throughput for models that fit its architecture Cerebras' WSE cuts interconnect overhead by putting the whole model on one wafer Google TPUs have run production workloads for years and are now sold externally via GCP So specialized hardware can win, sometimes even in production. The real question isn't whether something can beat a GPU, it's why none of these have dented Nvidia's share. 1. The capital barrier Custom silicon needs hundreds of millions in NRE cost, access to TSMC's leading-edge nodes with multi-year allocation queues, and several iterations before a design is commercially viable. That caps the field to hyperscaler balance sheets or venture funding measured in billions. The barrier isn't just the chip either. CUDA, the surrounding tooling, and production pipelines took a decade of capital and engineering to mature, and matching that means rebuilding all of it, not swapping a part. That's a second capital sink on top of the silicon itself. There's also a timing risk specific to fixed-function silicon: if the underlying model architecture shifts significantly, an ASIC taped out for today's transformer variant can become dead weight, while a GPU just needs a software update to run whatever comes next reasonably well. That risk hasn't actually played out,
AI 资讯
How Git Actually Works Under the Hood
Most developers use Git every day and understand almost none of it. That's not an insult, it's just the reality of how most people learn tools. You pick up the commands that get you through the day, you memorize the ones that fix the situations you keep breaking, and you build a working mental model that is almost entirely wrong at the mechanical level. The mental model most people carry looks something like this: Git tracks changes to files. When you commit, it saves a snapshot of what changed. Branches are pointers to different lines of work. That's roughly correct at a surface level, but it skips over the actual machinery in a way that leaves you confused every time something unexpected happens. Why does rebasing rewrite history? Why are commits immutable? Why does detached HEAD state exist? Why can you lose work in ways that feel impossible if Git is just tracking changes? The answers are all in the object model, and the object model is surprisingly simple once you sit with it. Git is a content-addressable filesystem Before any of the version control concepts, Git is a key-value store. You put content in, you get a hash back. You use that hash later to retrieve the content. That's the entire foundation, and everything else is built on top of it. The hash Git uses is SHA-1, producing a 40-character hexadecimal string. When you run git hash-object on a file, Git takes the content, prepends a small header describing the object type and size, and runs SHA-1 over the whole thing. The resulting hash is both the key and the identity of that content. Two files with identical content will always produce the same hash. A file whose content changes even slightly will produce a completely different hash. This is the first thing that breaks people's mental models. In most storage systems, identity is location: a file is "that file" because it lives at that path. In Git's object store, identity is content. The path a file lives at is separate metadata, not the file's identity
AI 资讯
Your web app is invisible to AI search (and ranking on Google won't fix it)
You did the hard part. You designed it, you built it, you shipped it. The product is good. And still, the users do not come. I have been in that exact spot more than once. You refresh the analytics, you tell yourself it is early, and quietly a worse question starts to form: what if people are not ignoring my app, what if they simply never see it? Here is the thing almost nobody tells builders in 2026. For a growing share of your future users, the front door to the internet is no longer a list of blue links. It is a sentence. Someone opens ChatGPT, Perplexity, or Google's AI Mode and types "what is the best tool for X." The model replies with a short list of names. If your product is not one of them, you do not exist in that moment. There is no page two to claw your way onto. There is one answer, and you are either in it or you are not. Three things are probably true about your app right now, and you cannot see any of them Your app might render blank to the machines that decide. If you built a single-page app (React, Vue, most modern stacks), the raw HTML a crawler receives can be an almost empty . Most AI crawlers do not run JavaScript. They read what your server sends and leave. To them, your beautiful app has no words, no product, no reason to be cited. You can rank number one on Google and still be missing from the answer. In one large 2025 study, roughly 68 percent of the pages cited in AI Overviews were not even in the top ten organic results. Ranking and being cited have quietly become two different games. Winning the old one no longer wins you the new one. A model may already be describing your product to strangers, and getting it wrong. A feature you do not have. A price that is out of date. A category that is not yours. You are being represented in rooms you will never enter, by a narrator you never hired, and the only way to fix the story is to give the machines a cleaner one to read. None of this shows up in your dashboard. That is what makes it dangerous
科技前沿
How to Avoid Spoilers Online and in Chats
You can minimize the risk of films and shows being spoiled for you by muting comments, conversations, and keywords on various platforms.
AI 资讯
Bundling a CLI Binary as a Tauri v2 Sidecar: Lessons from Building a Desktop App
When you build a desktop app with Tauri v2 , sooner or later you'll hit a question: how do I bundle and manage an external CLI binary inside my app? Maybe it's ffmpeg for video processing. Maybe it's a database engine. Maybe — as in my case — it's frpc , the reverse-proxy client from the popular frp project. This post walks through the full lifecycle: bundling, spawning, lifecycle management, and even self-updating the binary at runtime — all from Rust. 1. Declaring the Sidecar In tauri.conf.json , declare the binary under bundle.externalBin : { "bundle" : { "externalBin" : [ "binaries/frpc" ] } } Tauri identifies the target platform by a filename suffix convention . You need to place the correctly-named binary in your project: Platform Filename macOS (Apple Silicon) frpc-aarch64-apple-darwin macOS (Intel) frpc-x86_64-apple-darwin Windows (x64) frpc-x86_64-pc-windows-msvc.exe Tauri automatically strips the suffix at runtime and loads the right binary for the current platform. 2. Spawning the Process Use tauri_plugin_shell to spawn the sidecar: use tauri_plugin_shell ::{ ShellExt , process :: CommandEvent }; #[tauri::command] async fn start_frpc ( app : tauri :: AppHandle ) -> Result < (), String > { let sidecar = app .shell () .sidecar ( "frpc" ) .map_err (| e | e .to_string ()) ? ; let ( mut rx , child ) = sidecar .args ([ "-c" , "frpc.toml" ]) .spawn () .map_err (| e | e .to_string ()) ? ; // Store the child handle so we can kill it later app .state :: < std :: sync :: Mutex < Option < tauri_plugin_shell :: process :: CommandChild >>> () .lock () .unwrap () .replace ( child ); // Listen to stdout/stderr in a background task tauri :: async_runtime :: spawn ( async move { while let Some ( event ) = rx .recv () .await { match event { CommandEvent :: Stdout ( line ) => { // Parse log line, update UI state... } CommandEvent :: Stderr ( line ) => { /* ... */ } CommandEvent :: Terminated ( _ ) => { // Process exited — update state machine } _ => {} } } }); Ok (()) } The
AI 资讯
Java & AI: What Developers Need to Know
Stop the ReAct Chaos: Building Deterministic Multi-Agent Cycles with Spring AI Graph If you are still letting LLMs freely decide their next execution step in an unconstrained ReAct loop, you are burning cloud budget on infinite loops and non-deterministic failures. In 2026, enterprise-grade AI requires the strict guardrails of stateful, cyclic graphs where transitions are governed by code, not LLM vibes. Why Most Developers Get This Wrong Naive ReAct Loops: Relying entirely on prompt-based tool calling to determine flow, which inevitably derails after 3-4 turns. Stateless Agents: Passing massive, unmanaged chat histories back and forth instead of maintaining a single, thread-safe state object. Lack of Edge Controls: Failing to hardcode conditional transitions, letting the LLM hallucinate its way into non-existent API endpoints. The Right Way The solution is to model your multi-agent system as a deterministic, cyclic graph where the LLM only executes node-level tasks, while Java code controls the state transitions. Define an Immutable State: Use Java record types to represent the thread-safe state passed between nodes. Explicit Nodes and Edges: Map agents (e.g., Writer, Critic) to discrete nodes and use conditional routers to decide the next transition. Spring AI Graph API: Leverage Spring AI 1.2.0's StatefulGraph to manage state persistence and concurrent transitions out-of-the-box. Model Specialization: Use fast, cheap models (like Llama 3.3) for routing decisions, and reasoning models (like Claude 3.5 Sonnet) only for complex node tasks. Show Me The Code (or Example) // Define stateful graph with immutable State record var workflow = new StatefulGraph < AgentState >() . addNode ( "writer" , state -> writerAgent . call ( state )) . addNode ( "critic" , state -> criticAgent . call ( state )) . addEdge ( START , "writer" ) . addEdge ( "writer" , "critic" ) . addConditionalEdge ( "critic" , state -> { return state . isApproved () ? END : "writer" ; // Deterministic cy
AI 资讯
Nobody is monitoring Bluesky, so I built a mentions scraper for it
I wanted to know when people mention a brand on Bluesky. Simple ask. Turns out Brandwatch, Mention, Hootsuite, basically every social listening tool, still doesn't cover it. They're all busy with X and Instagram while Bluesky sits at 27M+ monthly users. So I looked at doing it myself and found out something most people miss: you don't need to scrape anything. Bluesky runs on the AT Protocol, which is open by design. Public posts are searchable through a documented endpoint. No login, no API key. GET https://api.bsky.app/xrpc/app.bsky.feed.searchPosts?q=YOUR_BRAND&sort=latest&limit=100 That returns full post objects. Text, author handle, timestamps, like/repost/reply counts, embedded links, hashtags. Everything you need. Two things that broke my first version Worth writing down because most tutorials get this wrong now: The public.api.bsky.app host that older guides point to returns 403 for search. Use api.bsky.app instead. As of July 2026, unauthenticated search rejects cursor pagination. Page one works fine, page two gets you a 403 with "request forbidden by administrative rules". The nasty part is it looks like rate limiting, but it isn't. The workaround: paginate by time. Use sort=latest , then pass until= with the createdAt of the oldest post from the previous page. Dedupe on uri because the boundary post shows up twice. If you don't want to maintain any of that I packaged the whole job as an Apify actor: Bluesky Mentions Scraper . Keywords in, clean JSON out. It handles the pagination and retry stuff above, filters replies if you want, scores basic sentiment, and can pull follower counts for each author so you can sort mentions by reach. Runs on a schedule, exports CSV, plugs into Slack or n8n through Apify's integrations. It also works as an MCP tool inside Claude or Cursor. Pricing is per result, $4 per 1,000 mentions. No subscription. What I actually monitor Brand and product names plus the common misspellings. Competitor names, because share of voice on Blu
AI 资讯
Quieting PHP 8.2+ deprecated noise from older WP-CLI — three layers to keep JSON parse clean
Our multi-site maintenance tool fires wp plugin list --format=json against the sites it manages. One day, against a specific shared host (Xserver in Japan), this call started failing — and the failure mode was unusually subtle. Both the SSH connection test and the WP-CLI path test ( wp --version ) came back green. Users saw "all diagnostics pass, but the actual operation fails," a frustrating asymmetry. Tracing it back, the root cause was PHP Deprecated warnings emitted by older WP-CLI (2.x) under PHP 8.2+ leaking into the JSON output. This post walks through the three-layer defense we used to structurally absorb the noise without losing real failures. What was happening — Deprecated warnings on stdout The raw output on a problem host looked like this: PHP Deprecated: Creation of dynamic property WP_CLI\Dispatcher\CompositeCommand::$longdesc is deprecated in phar:///usr/bin/wp/vendor/wp-cli/wp-cli/php/... [ {"name":"akismet","status":"active","update":"none", ...}, ... ] Since PHP 8.2, assigning to a dynamic property on a class without #[\AllowDynamicProperties] emits a Deprecated warning. Xserver's /usr/bin/wp (an older WP-CLI 2.x) leans on dynamic properties internally, so running it on PHP 8.2+ produces a steady stream of those warnings. Note: PHP 8.2's dynamic-property deprecation is a healthy direction for the language. But during the transition, you get many libraries that "warn but still work" — WP-CLI was one of them. The actual problem is the host's php.ini : depending on display_errors , those warnings end up on stdout instead of stderr . Calling wp plugin list --format=json returns stdout containing both the warnings and the JSON, and json_decode() fails on the mixed input. Why diagnostics stayed green but operations failed The frustrating asymmetry came from how each test was checking the output: SSH connection test : runs echo ok — passes as long as ok appears somewhere in stdout, extra lines are fine WP-CLI path test : runs wp --version — passes as lon
AI 资讯
Building a real-time gold & FX price ticker with WebSocket (Socket.IO)
If you build apps for jewelers, fintech dashboards, or e-commerce price automation, you eventually need one thing: reliable, low-latency gold and currency prices . Scraping fragile sources breaks constantly. A dedicated price API solves this. In this post I'll show how to consume real-time gold (gram, quarter, coin) and FX rates over both REST and WebSocket (Socket.IO) using the Hasfiyat Gold & Currency API . Why a price API instead of scraping? Stability — a documented contract instead of HTML that changes without notice. Low latency — prices are pushed as the market moves, not on a slow cron. Multiple sources with failover — if one provider drops, the feed keeps flowing. 1. Polling with REST The simplest integration: request the prices you need with your API key. curl -X GET \ 'https://api.hasfiyat.com/api/prices?symbols=HAS,GRAM,CEYREK' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Accept: application/json' // Node.js const res = await fetch ( " https://api.hasfiyat.com/api/prices?symbols=HAS,GRAM,CEYREK " , { headers : { Authorization : " Bearer YOUR_API_KEY " } } ); const data = await res . json (); console . log ( data ); REST is ideal for periodic reporting, server-side jobs, and updating e-commerce product prices. 2. Live updates with Socket.IO For price screens, signage, and mobile apps where every tick matters, keep a connection open and let the server push changes: import { io } from " socket.io-client " ; const socket = io ( " https://api.hasfiyat.com " , { auth : { token : " YOUR_API_KEY " } }); socket . on ( " gold_prices " , ( data ) => { // { symbol: "HAS", type: "Has Altın", buy: 2450.85, sell: 2455.10, timestamp: "14:32:01.045" } console . log ( data ); }); No polling, no hammering the server — each market move arrives instantly. 3. A minimal live ticker in the browser <div id= "gold" ></div> <script src= "https://cdn.socket.io/4.7.5/socket.io.min.js" ></script> <script> const socket = io ( " https://api.hasfiyat.com " , { auth : { token : " YOUR
AI 资讯
New Google commercial imagines a Declaration of Independence written with help from AI
Two hundred and fifty years after the signing of the Declaration of Independence, a new commercial asks: What if the Founding Fathers had access to Google Workspace?
AI 资讯
Your Guardrails Are a Firewall. Your Failures Are a Cascade
TL;DR— Most production AI teams build safety layers using the content-moderation mental model: classify input, classify output, block or pass. But the incidents that actually take down AI systems in production look like distributed-systems failures— retries amplifying bad state, cascading errors across agent steps, silent drift with no rollback path. Guardrails need to borrow from SRE, not from trust-and-safety. Ask a team how they handle AI safety in production and you'll get the same answer almost every time: an input classifier, an output classifier, maybe a moderation API bolted on the side. This is the content-moderation mental model— filter bad stuff in, filter bad stuff out. It's borrowed wholesale from trust-and-safety teams who spent a decade building spam filters and abuse detectors. It's also the wrong model for most of what actually breaks AI systems in production. The incidents that page you at 2am rarely look like a jailbreak slipping past a classifier. They look like distributed-systems failures: a retry loop that amplifies a bad tool call, a hallucinated intermediate result that poisons every downstream step, a silent shift in output distribution that nobody notices until a customer complains three weeks later. These are not content problems. They're systems problems, and they need systems solutions. The Cascade, Not the Jailbreak Consider a typical agent pipeline: retrieve context, call a model to plan, call tools, call a model again to synthesize, maybe loop if a tool fails. Each step has some non-zero error rate. In a single-call chatbot, that error rate is the whole risk surface. In a five-step agent chain, errors compound, and worse, they compound non-linearly because failed steps often trigger retries, and retries on a stateful action are not free. A model that hallucinates a tool argument doesn't just produce one bad output— it produces a bad state that the next step reasons over as if it were true. If that next step is another LLM call, it wi
AI 资讯
Fixing the 550 SPF Check Failed Error: A Technical Step-by-Step Troubleshooting Guide
Understanding the 550 SPF Check Failed Error The "550 SPF Check Failed" error indicates that a receiving mail server rejected an incoming email. This rejection occurs because the sender's domain failed its Sender Policy Framework (SPF) validation. SPF is an email authentication protocol defined in RFC 7208 . SPF helps prevent email spoofing. It allows domain owners to specify which mail servers are authorized to send email on behalf of their domain. Receiving mail servers perform an SPF check by querying the sender's DNS for an SPF TXT record. If the sending server's IP address is not listed in the domain's SPF record, the SPF check fails. The receiving server then rejects the email based on its configured policy, often resulting in a 550 error. This error protects recipients from unauthorized emails and enhances email security. Initial Diagnosis: Identifying the Root Cause Diagnosing an SPF failure requires examining the bounce message and the domain's DNS records. The bounce message often provides specific details about the SPF failure. Look for phrases like "SPF validation failed," "unauthorized sender," or "IP address not permitted." Common reasons for a 550 SPF Check Failed error include: Missing SPF Record: No SPF TXT record exists for the sending domain. Incorrect SPF Syntax: The SPF record contains errors, making it unreadable or invalid. Incomplete SPF Record: The SPF record does not list all legitimate sending IP addresses or hostnames. DNS Lookup Limit Exceeded: The SPF record requires more than 10 DNS lookups, violating RFC 7208. DMARC Policy Enforcement: A DMARC (Domain-based Message Authentication, Reporting, and Conformance) policy ( RFC 7489 ) with p=reject or p=quarantine is in place, enforcing strict SPF failure handling. To begin diagnosis, use our SPF checker to verify your domain's SPF record and its validity. This tool quickly identifies syntax errors and lookup issues. Step-by-Step Troubleshooting and Resolution Resolving SPF failures involves
AI 资讯
Midjourney wants Hollywood studios to reveal the details of their AI usage
As part of an ongoing legal dispute with three Hollywood studios, Midjourney is seeking to compel those studios to reveal how they use AI themselves.
AI 资讯
Configuring DMARC p=quarantine: A Technical Step-by-Step Guide to Secure Your Domain and Improve Deliverability
Introduction to DMARC and the p=quarantine Policy DMARC (Domain-based Message Authentication, Reporting, and Conformance), defined in RFC 7489 , is an email authentication protocol. It builds upon SPF and DKIM to provide domain owners with the ability to protect their domain from unauthorized use. DMARC enables senders to specify how receiving mail servers should handle unauthenticated emails originating from their domain. It also provides a mechanism for receiving servers to report back to the domain owner about authentication results. DMARC policies dictate the action receiving mail servers should take when an email fails DMARC authentication. The three primary policies are: p=none : Monitor mode. Receiving servers take no action on failed messages but send reports. This is the initial deployment phase. p=quarantine : Receiving servers should treat failed messages as suspicious. They are typically placed in the recipient's spam folder or flagged for further review. p=reject : Receiving servers should outright reject messages that fail DMARC authentication. This is the strongest enforcement policy. Implementing p=quarantine is a critical step towards full domain protection. It allows domain owners to mitigate spoofing and phishing attempts without immediately blocking legitimate, but misconfigured, email streams. This policy provides a balance between security enforcement and minimizing potential deliverability disruptions. Prerequisites for DMARC p=quarantine Implementation Before deploying a p=quarantine policy, proper configuration of SPF and DKIM is mandatory. DMARC relies on these underlying authentication mechanisms and their alignment with the sending domain. SPF (Sender Policy Framework) SPF, specified in RFC 7208 , allows domain owners to publish a list of authorized sending IP addresses in their DNS. Receiving mail servers check the SPF record to verify if an incoming email originated from an authorized server. An SPF record is a TXT record at the root of
AI 资讯
How to Compress Images in the Browser with Canvas API (No Uploads, No Server)
How to Compress Images in the Browser with Canvas API Every image you upload to a "free" online compressor is sent to a server — often without you knowing what happens to it afterward. For a tool that processes your private photos, that's a terrible design. Here's how to build (or use) an image compressor that runs entirely in the browser using the HTML5 Canvas API. No uploads, no server costs, and unlimited file sizes. The Core Technique: Canvas toBlob() The key API is HTMLCanvasElement.toBlob() : js const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = () => { canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; ctx.drawImage(img, 0, 0); canvas.toBlob((blob) => { const url = URL.createObjectURL(blob); }, 'image/jpeg', 0.8); }; img.src = 'your-image.jpg'; The second parameter is the MIME type (image/jpeg, image/png, image/webp, image/avif). The third is quality (0–1). Step-Down Resizing for Large Images If you're compressing a 6000×4000 px photo, drawing it at full resolution onto a canvas can eat 70+ MB of memory. Step-down resizing halves the dimensions repeatedly: function stepDownEncode(img, maxDim, quality) { let w = img.naturalWidth; let h = img.naturalHeight; let src = img; while (w > maxDim * 2 || h > maxDim * 2) { w = Math.floor(w / 2); h = Math.floor(h / 2); const temp = document.createElement('canvas'); temp.width = w; temp.height = h; temp.getContext('2d').drawImage(src, 0, 0, w, h); src = temp; } const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; canvas.getContext('2d').drawImage(src, 0, 0, w, h); return new Promise((resolve) => { canvas.toBlob((blob) => resolve(blob), 'image/jpeg', quality); }); } This prevents memory crashes and actually produces better quality (step-down preserves more detail than a single jump). Comparing Real-World Results Format Avg Original Avg Compressed Avg Savings JPEG → JPEG (Q80) 3.2 MB 0.8 MB 75% PNG → We
AI 资讯
AGENTS.md, Hands-On: Build One Step by Step (and Watch an Agent Use It)
In the field guide I covered what an AGENTS.md is and what belongs in it. This is the hands-on follow-up: we'll build a complete AGENTS.md for a real project, one section at a time, then point an AI coding agent at it and watch the difference it makes. By the end you'll have a working file — and you'll have seen it pay off. New to AGENTS.md? It's a single Markdown file at the root of your repo that tells AI coding agents how to work in it — build steps, tests, conventions, guardrails. The "why" behind each section is in the field guide . The project we'll use We'll write the AGENTS.md for a small but real service: a URL shortener API in Python — FastAPI, SQLite, pytest. A couple of endpoints, a thin data layer, a test suite. Follow along with this, or swap in your own repo — the steps are identical. Its shape: linkshort/ app/ main.py # FastAPI routes db.py # SQLite access models.py # Pydantic models migrations/ # generated SQL — not hand-edited tests/ requirements.txt Step 0 — Start with an empty file At the repo root: touch AGENTS.md That's the whole step. We'll fill it in one section at a time, building toward a file an agent can read in thirty seconds. Step 1 — Orientation: one line Tell the agent what it's looking at. Add: # AGENTS.md A URL shortener API in Python — FastAPI, SQLite, pytest. One sentence sets the agent's priors: it knows the language, framework, and storage before it reads a single line of code. Step 2 — Setup and run The agent can't help if it can't start the project. Add the real, copy-pasteable commands: ## Setup python -m venv .venv && source .venv/bin/activate pip install -r requirements.txt ## Run uvicorn app.main:app --reload # http://localhost:8000 Use the commands that actually work in your repo — no placeholders. Step 3 — Tests: the agent's feedback loop This is the most important section, because tests are how the agent checks its own work. Add: ## Test — all must pass before a change is done pytest ruff check . mypy app Now the agent
AI 资讯
Building Instant Translation Assistance for Book Translations with Python and LLMs
How we integrated real-time phrase translation feedback into our AI-powered book translation workflow, and what we learned about latency, context, and prompt engineering. When we launched LectuLibre, our AI-powered book translation platform, users loved the quality of full-chapter translations. But they kept asking for something else: while reading a partially translated book, they'd stumble on an untranslated phrase or an awkward auto-translation and want to quickly get a better version without leaving the page. So we built 即时翻译求助 (Instant Translation Help)—a feature that lets readers highlight any phrase and get a context-aware, human-quality translation within seconds, along with a brief explanation of tricky parts. Here's how we built it, the technical challenges we faced, and the lessons we learned about stitching LLMs into a real-time reading experience. Problem: Real-time, Context-Aware Translation Inside a Book Most web apps offer generic translation via API calls—send a sentence to Google Translate, get a result. But that doesn't work for literary texts. A phrase like "She let the cat out of the bag" needs to be translated idiomatically, and the appropriate rendering depends heavily on the surrounding paragraphs (is the tone formal? sarcastic? part of a metaphor chain?). Our existing translation pipeline processes entire chapters in bulk with carefully crafted prompts, but for instant help, we needed sub-second latency while preserving that same depth of context. Our Approach: Server‑Sent Events and a Smart Prompt Buffer We chose Server-Sent Events (SSE) over WebSockets because the communication is one-directional (server pushes translation tokens) and SSE is simpler to implement with FastAPI. The client (a React app) sends a POST request with: The phrase to translate The book ID and the exact location (chapter/paragraph index) The target language Our backend retrieves the surrounding text from PostgreSQL (we store the original book in chunks), feeds a care