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
AI 资讯
The Global AI Hardware Gamble: Korea $550B + Japan $6B + Qualcomm Challenges NVIDIA - What This Means for Investors and Builders
Over the past week, the AI hardware news I've been tracking adds up to more than $610 billion in capital deployed globally — in just seven days. Not valuations. Not market cap. Actual capital expenditure commitments. Korea $550B, Japan $6B, Qualcomm's new accelerator, Kawasaki Heavy Industries' $1B AI infrastructure bond — this round of moves has already surpassed the wildest half-year of the 2000 dot-com bubble in scale. But this time the money isn't flowing into web pages. It's flowing into chips, memory, and power. Watching all of this over the past few days, I've been thinking: for investors and for builders like us making products on top of AI, what does this gamble actually mean? The Real Story Behind AI Training Bottlenecks: From GPU Scarcity → Memory Scarcity → Power Scarcity Honestly, everyone watches AI through the lens of models, but the real bottleneck was never the models — it's been the hardware. From 2023 to 2025, the bottleneck shifted from GPU scarcity to memory scarcity, and is now pushing toward power scarcity. When GPUs were tight, everyone scrambled for H100s and NVIDIA raked it in — but the part that actually throttled the H100 wasn't the GPU core, it was the HBM high-bandwidth memory. On the B200, the HBM3E stacked on top has its capacity locked up entirely by NVIDIA at SK Hynix, while Samsung is chasing hard but its yields can't keep up. That's why South Korea just committed $518B to build 4 memory fabs plus $52B for the central regions, totaling $550B ( TechCrunch ). This isn't just about filling upstream capacity — the key is that Samsung + SK Hynix are trying to flip themselves from being NVIDIA's downstream suppliers into becoming the dominant players in AI hardware. Why did downstream hardware investment kick off so late? Because for the past two years people were still watching and waiting to see if "this AI hype cycle would cool down again." By 2026, GPT-6, Claude 4, and Gemini 3 are all live, inference costs have come down, user numbe
AI 资讯
Solon 4.0 ReActAgent: A Practical Guide to Building AI Agents That Think and Act
If you've ever wanted an AI that doesn't just chat but actually does things — queries databases, calls APIs, makes decisions, and learns from results — you're in the right place. In this tutorial, I'll show you how to build production-ready AI agents using Solon 4.0's ReActAgent . By the end, you'll have built an agent that can reason through complex problems, use external tools, and adapt its behavior based on real-world feedback. What Makes ReActAgent Different? Traditional LLMs are great at generating text, but they hit a wall when they need to interact with the real world — checking a database, fetching live data, or performing calculations. ReActAgent (Reason + Act) breaks through that wall. It implements a cognitive loop: Thought → Action → Observation → (repeat or finish) The agent thinks about what to do next, acts by calling a tool, observes the result, and decides whether to continue or deliver the final answer. This isn't just theory. Solon's ReActAgent has been used in production for automated customer support, intelligent data analysis, and multi-step workflow automation. 1. Adding the Dependency First, add the solon-ai-agent module to your project: <dependency> <groupId> org.noear </groupId> <artifactId> solon-ai-agent </artifactId> </dependency> Note : If you're using Solon's parent POM, the version is managed automatically. Otherwise, use the latest Solon version. 2. Building a ChatModel (The Agent's Brain) Every agent needs a "brain" — a ChatModel that powers reasoning. Let's build one using the fluent API: import org.noear.solon.ai.chat.ChatModel ; ChatModel chatModel = ChatModel . of ( "https://api.moark.com/v1/chat/completions" ) . apiKey ( "your-api-key-here" ) . model ( "Qwen3-32B" ) . build (); You can also configure it via YAML and inject it: solon.ai.chat : demo : apiUrl : " http://127.0.0.1:11434/api/chat" provider : " ollama" model : " llama3.2" @Inject ( "${solon.ai.chat.demo}" ) ChatConfig chatConfig ; ChatModel chatModel = ChatModel . o
AI 资讯
Convertir des images en lot (HEIC, WebP, JPG) gratuitement — Guide pratique
📖 Article original : GitHub Gist Un guide technique par Mohamed ben mallessa Le problème Recevoir un dossier de 500 fichiers HEIC à convertir en WebP pour un site web est une situation courante pour tout développeur. Les solutions traditionnelles ont leurs limites : ImageMagick nécessite des codecs spécifiques, les convertisseurs en ligne sont limités en taille, et le traitement manuel est exclu à cette échelle. La solution Photopea (Photoshop gratuit dans le navigateur) supporte nativement tous les formats d'image courants. En l'utilisant comme moteur de conversion piloté par script, on obtient un pipeline batch rapide et fiable. Formats supportés Entrée Sorties possibles HEIC / HEIF JPG, PNG, WebP JPEG WebP, PNG, PSD PNG JPG, WebP WebP PNG, JPG PSD PNG, JPG, WebP SVG PNG, JPG TIFF PNG, JPG, WebP Pipeline Dossier source (500 HEIC) → Photopea → Dossier sortie (500 WebP) Le script préserve la structure des sous-dossiers, applique le redimensionnement et la qualité configurés, et livre les fichiers organisés. Paramètres typiques --format webp # Format de sortie --quality 80 # Qualité (1-100) --resize 1920 # Redimensionnement (côté long) --output ./web/ # Dossier de destination Avantages Un seul outil pour tous les formats d'entrée Aucun codec à installer (Photopea gère tout nativement) Gratuit et sans abonnement Local — les fichiers ne quittent pas votre machine Structure préservée — l'arborescence est conservée Mohamed ben mallessa — Full-stack developer & solutions B2B 🔗 GitHub · LinkedIn opensource #webp #python #tutorial 💻 Vous avez un projet technique ? Développement full-stack, automatisation IA, solutions B2B sur mesure. 🔗 GitHub 💼 LinkedIn 🎨 Behance Article initialement publié sur GitHub Gist
AI 资讯
Solon 4.0 ChatModel: A Practical Guide to Building LLM-Powered Applications
If you've ever tried integrating a large language model (LLM) into a Java application, you've probably written a lot of boilerplate: HTTP clients, JSON parsing, streaming handling, session management. Solon 4.0's ChatModel abstracts all of that away with a clean, builder-oriented API. In this guide, I'll walk through building real, working AI features using ChatModel — from a simple chat call to a streaming chatbot with conversation memory. 1. What Is ChatModel? ChatModel (package org.noear.solon.ai.chat ) is a unified LLM client in Solon's AI ecosystem. Instead of writing raw HTTP calls for different model providers, you use a single API that supports: Synchronous calls — one-shot request, full response Streaming calls — reactive streaming via Project Reactor ( Flux<ChatResponse> ) Tool/Function Calling — let the LLM invoke your Java methods Chat Sessions — automatic conversation memory Multi-modal messages — text, images, audio Dialect adaptation — works with OpenAI, Ollama, Anthropic, Gemini, DashScope, and more The best part? It uses a dialect pattern — you point it at any compatible LLM endpoint, and it adapts automatically. 2. Setting Up Add the dependency to your pom.xml (no parent POM needed — Solon works standalone): <dependency> <groupId> org.noear </groupId> <artifactId> solon-ai </artifactId> <version> ${solon.version} </version> </dependency> This pulls in all built-in dialects (OpenAI, Ollama, Gemini, Anthropic, DashScope). 3. Configuration 3.1 Via YAML (Recommended) solon.ai.chat : demo : apiUrl : " http://127.0.0.1:11434/api/chat" # Full URL, not baseUrl provider : " ollama" # Dialect identifier model : " llama3.2" # Model name headers : x-demo : " demo1" Then create a @Bean to get a ready-to-use ChatModel : import org.noear.solon.ai.chat.ChatConfig ; import org.noear.solon.ai.chat.ChatModel ; import org.noear.solon.annotation.Bean ; import org.noear.solon.annotation.Configuration ; import org.noear.solon.annotation.Inject ; @Configuration public cla
AI 资讯
The only AI glossary you’ll need this year
The rise of AI has brought an avalanche of new terms and slang. Here is a glossary with definitions of some of the most important words and phrases you might encounter.
开发者
Google DeepMind Unionization Talks Are Off to a Rocky Start
During negotiations on Wednesday, employees voiced frustrations with what they consider an unwillingness among executives to engage meaningfully with the prospect of unionization.
AI 资讯
Effort Levels in Practice: I Benchmarked low Through max on Real Tasks
The current Claude models give you an effort knob with five settings: low , medium , high , xhigh , max . The docs tell you what each is for. I wanted numbers, so I ran the same three real tasks across all five levels and measured tokens, latency, and quality. The results changed how I set effort, and one of them surprised me. Here is the data and what I do with it now. What effort controls Effort is not just "how much the model thinks." It controls overall token spend: how much it thinks and how it acts. Lower effort means fewer, more consolidated tool calls, less preamble, terser output. Higher effort means more exploration before answering. The default is high if you omit it. const response = await client . messages . create ({ model : " claude-opus-4-8 " , max_tokens : 16000 , thinking : { type : " adaptive " }, output_config : { effort : " medium " }, // the knob messages , }); The three tasks I picked tasks that span the range of what I actually do: Classification : label a contract finding as low/medium/high/critical. Short, scoped. Code generation : write a TypeScript function with edge-case handling. Medium difficulty. Multi-step audit : analyze a 200-line contract for vulnerabilities across functions. Hard, agentic. I ran each at all five effort levels, three times, and averaged. I scored quality against a known-correct answer for tasks 1 and 3, and by manual review for task 2. The results Task 1, classification. Quality was flat across every effort level. The right label is the right label, and the model nailed it at low just as well as at max . But token usage climbed steeply: max used roughly 8x the tokens of low for an identical answer. Latency tracked tokens. The lesson: for genuinely simple, scoped tasks, high effort is pure waste. I set classification to low . Task 2, code generation. Quality improved from low to high , then plateaued. At low the model sometimes skipped an edge case. At high it caught them. xhigh and max produced essentially the sam
AI 资讯
Why pandas_market_calendars Fails for Indian Markets (and what to use instead)
Indian algo traders and quant developers hit the same wall: they reach for pandas_market_calendars , set up XNSE , and get back answers that are silently wrong for three segments that matter most in India. Here is what breaks and what to use instead. The three failure cases 1. MCX evening sessions MCX commodity markets (crude oil, natural gas, gold, silver) run until 23:30 IST. pandas_market_calendars has no MCX calendar. Any check after 15:30 returns a wrong answer. # pandas_market_calendars — no MCX at all # mcal.get_calendar("MCX") → KeyError # aion-indian-market-calendar — works correctly from aion_indian_market_calendar import IndiaMarketCalendar from datetime import datetime from zoneinfo import ZoneInfo cal = IndiaMarketCalendar . bundled ( 2026 ) tz = ZoneInfo ( " Asia/Kolkata " ) cal . is_market_open ( " MCX " , datetime ( 2026 , 6 , 18 , 20 , 0 , tzinfo = tz )) # True 2. NSE Currency Derivatives (CDS) — wrong hours, wrong holidays USDINR, EURINR, GBPINR, JPYINR futures and options trade on NSE CDS from 09:00 to 17:00 IST — 90 minutes longer than NSE equity. CDS also has a separate holiday calendar. pandas_market_calendars has no CDS calendar. Using XNSE gives you wrong close times and potentially wrong holiday answers for any currency derivative workflow. from aion_indian_market_calendar import IndiaMarketCalendar cal = IndiaMarketCalendar . bundled ( 2026 ) # These resolve correctly to their respective segments cal . is_market_open ( " USDINR " , at ) # NSE_CURRENCY_DERIVATIVES: closes 17:00 cal . is_market_open ( " NSE " , at ) # NSE_EQUITY: closes 15:30 cal . is_market_open ( " MCX " , at ) # MCX: closes 23:30 3. Muhurat trading (Diwali special session) On Diwali, NSE runs a one-hour equity session in the evening. pandas_market_calendars marks this day as a holiday. Schedulers that rely on it will skip execution entirely. cal = IndiaMarketCalendar . bundled ( 2026 ) events = cal . events_on ( " 2026-11-08 " , exchange = " NSE " ) # Returns the Muhurat t
AI 资讯
Presentation: Fine Tuning the Enterprise: Reinforcement Learning in Practice
The speakers discuss Agent RFT, OpenAI’s platform for fine-tuning reasoning models via real-time tool interactions and custom reward signals. They explain how reinforcement learning solves complex credit assignment challenges within the context window. They share enterprise success stories, showing how Agent RFT eliminates long-tail token loops and drives extreme efficiency. By Wenjie Zi, Will Hang
AI 资讯
The 2026 AI CLI Landscape: Claude Code, Gemini CLI (Antigravity CLI), and OpenClaw
Terminal-based AI agents have evolved considerably over the past few months, and several changes are significant enough that developers relying on these tools should be aware of them. Most notably, Google has begun retiring Gemini CLI for individual users in favor of Antigravity CLI — a closed-source successor that has drawn some pushback from the community that built out Gemini CLI's open-source ecosystem. Meanwhile, Claude Code has moved to the Opus 4.8 and Fable 5 models with a 1M-token context window, and OpenClaw, the open-source "always-on" agent, has grown into one of the most-starred projects on GitHub — alongside a documented CVE worth knowing about before deployment. I've just published an updated, fact-checked comparison covering: What actually changed with Gemini CLI's retirement, and what it means if you have scripts or CI/CD pipelines depending on it Claude Code's current model lineup, context window, and new Dynamic Workflows feature OpenClaw's architecture, extensibility via ClawHub, and the security considerations that come with deep system access A full feature-comparison table (cost, context window, open-source status, setup complexity) A practical case study walking through how all three tools can work together on a real project Would be curious to hear which of these you're using day-to-day, and whether the Gemini → Antigravity transition has affected your workflow. Full article here: Devlycan - Technology & Programming Insights Devlycan - Technology, programming, AI, lifestyle, and future trends—simple insights for the new digital generation. devlycan.com
AI 资讯
I Spent 30 Days Comparing Startup and Enterprise AI APIs
I Spent 30 Days Comparing Startup and Enterprise AI APIs Look, I'm just a dude building a SaaS side project. Not enterprise, not Fortune 500, just me and a few friends trying to ship something useful. So when I started hitting AI API walls, I went down the rabbit hole of figuring out what the heck to do. And honestly? Most guides out there are written by people who clearly have never had to choose between buying groceries or paying for OpenAI credits. They're either too corporate ("here's our enterprise procurement guide!") or too naive ("just use the cheapest API!"). So I figured I'd write the guide I WISH existed when I started. And I'm gonna throw in some enterprise stuff too because I consulted for a bigger company last year and saw what THEY deal with. Different worlds, I tell ya. Let me break this down properly. Why I Almost Just Used DeepSeek Directly Okay so here's the thing. When I first started, I was like "DeepSeek is dirt cheap, let me just sign up there and call it a day." I mean, the pricing was wild. Like cents per million tokens. How could I lose? Then I tried to actually sign up. Chinese phone number required. WeChat Pay or Alipay only. No PayPal. No Visa. Nothing. And I get it, that's their home market, but for me sitting here in my apartment in the US? Absolute dead end. So I started looking at aggregators. Tried like four of them. Some had weird pricing. Some had models that didn't actually work. One of them straight up charged me for tokens I never used (still salty about that). Then I landed on Global API and honestly I gotta say, it just worked. Email signup, PayPal, and I could test DeepSeek AND Claude AND Qwen all with one key. That's when I realised going direct to providers is kind of a trap if you're small. Let me show you the actual problem with going direct. The "Go Direct" Trap Here's what happens when you sign up direct with various providers: Problem What Happens to You Locked to one vendor Your whole app depends on their uptime Paym
开发者
Last chance to apply — Startup Battlefield Australia applications close July 6
If you're going to apply for Startup Battlefield Australia, now is the time. Applications close July 6, and once the deadline passes, the opportunity is gone.
AI 资讯
Gate the Statement, Not the Tool Name
The original safety gate on the Dolt-over-MCP plugin tried to keep a Claude Code agent harmless by excluding "history-affecting tools" from its MCP grant. It was the wrong granularity, and it did nothing. MCP exposes the entire database through one tool — query / exec — and that tool carries every SQL verb. SELECT rides it. So does CALL DOLT_PUSH , CALL DOLT_RESET('--hard') , DROP DATABASE , and CALL DOLT_BRANCH('-D', 'main') . Excluding "dangerous tools" from the grant accomplishes nothing, because the dangerous verbs live inside the one tool you already granted. The destructive operations were never separate tools to exclude. This is the reframe the whole Phase 0 hardening pass turned on: a tool-name allowlist is meaningless for any tool that carries a sub-language. SQL is a sub-language. So is the shell behind a Bash tool. So is anything behind an eval . If the tool can run arbitrary statements in some grammar, the only boundary that means anything is one that reads the statement. It is the move from tool-name allowlisting to capability-based security: the grant stops being "you may call the query tool" and becomes "you may run these statement classes inside it." Why not just allowlist the safe tools? Because there is exactly one tool, and it is not safe or unsafe — it is whatever statement you hand it. You cannot partition a single door into a safe door and a dangerous door by naming. The same logic kills the next-obvious fix: a denylist of dangerous verbs. Blacklist DOLT_PUSH , DOLT_RESET , DROP ... and miss DOLT_REBASE , or the proc Dolt ships next quarter, or a CALL whose name your regex didn't anticipate. A denylist is only as good as your imagination on the day you wrote it. The fix inverts that. You add safety by enumerating what is safe, not by blacklisting what is dangerous. Anything you cannot positively classify as safe is treated as the most dangerous thing it could be. Default-deny the unknown. It's least privilege applied to a grammar: the agent get
AI 资讯
Meta quietly launches vibe-coded gaming app Pocket
Meta has quietly launched Pocket, an experimental AI app that lets users generate and share interactive mini games using text prompts.
AI 资讯
Anthropic is discussing a new custom chip with Samsung
The news comes about a week after OpenAI announced its own custom AI chip in a partnership with Broadcom.
AI 资讯
Can Cursor Remain a Platform for OpenAI and Anthropic’s Models Inside SpaceX?
Cursor hopes to continue offering third-party AI models after it's acquired by SpaceX, testing the relationships between frontier AI labs.
AI 资讯
FAA proposal: Supersonic airliners can fly over US cities if they’re quiet
New US rules would legalize quiet supersonic flights without the sonic boom.