AI 资讯
QLoRA: Fine-Tuning a 7B Model on a 16GB GPU (It Shrank to 5.4GB in Front of Me)
In Part 2 , LoRA let me fine-tune a 1.5B model by freezing it and training tiny adapters. But the frozen base still sat in memory in 16-bit (~3GB). Now I wanted to go to Qwen2.5-7B — and hit a wall that LoRA alone doesn't solve. The problem A 7B model is ~15GB in 16-bit precision. A free-tier T4 GPU has 16GB. It would barely load, with no room left to actually train. The QLoRA insight QLoRA asks the question that naturally follows from LoRA: the base is frozen and only ever read — so why store it in full precision? So you quantize the frozen base to 4-bit (NF4, a format tuned for how neural-net weights are distributed) and run the LoRA adapters on top in normal precision. The base shrinks dramatically; the trainable part stays small and precise. from transformers import BitsAndBytesConfig bnb_config = BitsAndBytesConfig ( load_in_4bit = True , bnb_4bit_quant_type = " nf4 " , # NormalFloat4 bnb_4bit_use_double_quant = True , # quantize the quant constants too bnb_4bit_compute_dtype = torch . float16 , # dequantize to fp16 for the matmuls ) model = AutoModelForCausalLM . from_pretrained ( MODEL_ID , quantization_config = bnb_config , device_map = " auto " ) Each flag earns its place: load_in_4bit — store frozen weights in 4 bits instead of 16. nf4 — a 4-bit type matched to the bell-curve distribution of neural-net weights (better than plain int4). double_quant — quantize the quantization constants too, for a bit more savings. compute_dtype — dequantize to fp16 for the actual matmuls, so storage is 4-bit but compute stays precise. The moment it clicked One line of output: loaded in 4-bit. footprint: 5.44 GB I downloaded 15.2GB of weights and they sat in memory as 5.44GB. A model that couldn't be loaded for full fine-tuning was now training on a single consumer GPU — with room to spare. (The download is still 15GB; bitsandbytes quantizes on the fly during load.) The QLoRA-standard recipe Two more pieces beyond Part 2's LoRA setup: prepare the quantized model for trainin
AI 资讯
I Fixed the "AI Commit Messages" Problem in 20 Lines of Python
You've probably seen that trending post — "I Asked AI to Write My Commit Messages and It Was Embarrassing." Same. But instead of accepting embarrassing output, I fixed it. Here's the thing: the problem isn't AI writing commit messages. The problem is how you ask it. One clear system prompt + the actual diff = surprisingly good results. The Setup No new packages. No API key. If you have Claude Code , you're already set. #!/usr/bin/env python3 import subprocess SYSTEM = ( " You are a git commit message generator. " " Output ONLY the commit message — no explanation, no markdown, no quotes. " " Follow Conventional Commits: type(scope): subject. " " Types: feat, fix, docs, style, refactor, test, chore. " " Subject: imperative, lowercase, max 72 chars. " ) diff = subprocess . check_output ([ " git " , " diff " , " --staged " ], text = True ) if not diff . strip (): print ( " Nothing staged. Run `git add` first. " ) raise SystemExit ( 1 ) msg = subprocess . check_output ( [ " claude " , " -p " , SYSTEM + " \n\n " + diff ], text = True , ). strip () print ( msg ) That's it. 20 lines. Uses the claude CLI under the hood — no API key, no config, just your existing Claude Code OAuth session. Why It Works The system prompt does the heavy lifting. Three constraints: Output ONLY the commit message — no preamble, no explanation Follow Conventional Commits — feat , fix , chore , etc. max 72 chars — keeps it readable in git log The diff is the context. You're not asking "write a commit message". You're asking "given these exact changes, what happened?" That's a much more answerable question. Usage # No setup needed if you have Claude Code. Just: git add . python /path/to/git_commit.py # → feat(server): add AI commit message generator via Claude CLI Or wire it into a git alias: git config --global alias.ai '!python /path/to/git_commit.py' # git ai The Results Before: update stuff fix bug WIP added the thing After: feat(api): add generate_commit_message tool to MCP server fix(auth): ha
AI 资讯
Gelişmiş Veri İşleme (Python)
Gelişmiş Veri İşleme (Python) Sıralama, Filtreleme ve Arama – Profesyonel Veri Manipülasyonu Rehberi Python’da veri işleme, sadece döngülerden ibaret değildir. Modern Python yaklaşımı; fonksiyonel programlama araçları , yüksek seviyeli built-in fonksiyonlar ve lambda ifadeleri ile daha kısa, daha okunabilir ve daha performanslı çözümler üretmeyi hedefler. Bu bölümde dört kritik alanı derinlemesine inceleyeceğiz: sorted() ile gelişmiş sıralama lambda ile karmaşık veri yapıları üzerinde sıralama filter() ve map() ile fonksiyonel veri dönüşümü any() ve all() ile toplu doğrulama (validation) Her bölümde gerçek dünya senaryoları ve hands-on örnekler olacak. 1. sorted() Fonksiyonu — Gelişmiş Sıralama Motoru 1.1 Temel Yapı sorted ( iterable , key = None , reverse = False ) Parametreler: iterable: Liste, tuple, set vb. key: Sıralama kriteri (fonksiyon) reverse: True → büyükten küçüğe 1.2 Basit Sıralama ```python id="s1" sayilar = [5, 1, 9, 3, 7] sonuc = sorted(sayilar) print(sonuc) --- ## 1.3 Ters Sıralama ```python id="s2" sayilar = [5, 1, 9, 3, 7] print(sorted(sayilar, reverse=True)) 1.4 Tuple Sıralama ```python id="s3" veri = (10, 5, 20, 15) print(sorted(veri)) --- ## 1.5 String Sıralama (ASCII mantığı) ```python id="s4" kelimeler = ["python", "ai", "data", "backend"] print(sorted(kelimeler)) 2. key Parametresi — Sıralamanın Beyni sorted() fonksiyonunun gerçek gücü burada başlar. 2.1 String Uzunluğuna Göre Sıralama ```python id="k1" kelimeler = ["python", "ai", "veri", "makineöğrenmesi"] sonuc = sorted(kelimeler, key=len) print(sonuc) --- ## 2.2 Sayıların Moduna Göre Sıralama ```python id="k2" sayilar = [10, 3, 7, 21, 14, 9] sonuc = sorted(sayilar, key=lambda x: x % 5) print(sonuc) 2.3 Tuple Sıralama (Gerçek Dünya) ```python id="k3" urunler = [ ("Laptop", 45000), ("Mouse", 500), ("Monitör", 12000) ] sonuc = sorted(urunler, key=lambda x: x[1]) print(sonuc) --- ## 2.4 Çok Katmanlı Sıralama Fiyat → sonra isim ```python id="k4" urunler = [ ("Laptop", 45000), ("Mouse", 500),
AI 资讯
Use Unix Domain Sockets on Windows Python: Building an AF_UNIX Compatibility API
Python provides socket.AF_UNIX , asyncio.open_unix_connection() , and asyncio.start_unix_server() for working with Unix Domain Sockets on Unix-like operating systems. On Windows, however, support for Unix Domain Sockets tends to depend on the Python version and runtime environment. In particular, differences become apparent when trying to use the higher-level asyncio APIs in the same way as on Unix. To address this, I created a compatibility layer that hides the differences between Unix and Windows and allows AF_UNIX sockets to be used through a largely identical API. This article covers two types of APIs: An asyncio -based AF_UNIX compatibility API A synchronous socket -based AF_UNIX compatibility API Goal The objective is straightforward. On Unix, use the standard library APIs as-is. On Windows, fill in the missing functionality so that application code can remain as unified as possible. For example, on Unix you can write: reader , writer = await asyncio . open_unix_connection ( path ) And on the server side: server = await asyncio . start_unix_server ( handle_client , path ) The goal is to preserve this style of programming on Windows as much as possible. What Was Built The compatibility layer consists of two major components. 1. Asyncio Version This is the asynchronous implementation designed to match the asyncio Unix Domain Socket APIs. The main APIs are: await open_unix_connection ( path , * , limit = ...) await start_unix_server ( callback , path , * , limit = ..., backlog = ...) await create_unix_connection ( protocol_factory , path , ...) await create_unix_server ( protocol_factory , path , ...) install () On Unix-like systems, these simply delegate to the standard asyncio implementation. On Windows, they use Winsock AF_UNIX sockets and combine WSAEventSelect with event-loop handle waiting to implement asynchronous operations. 2. Synchronous Socket Version This version provides a traditional blocking-socket-style API without using asyncio . The main APIs ar
AI 资讯
Why I Built My Own Rate Limiting Library for FastAPI
This was originally posted on my blog . I was not planning to build a rate limiting library. I had a FastAPI project, I needed rate limiting, I reached for SlowAPI, which is the most popular choice for FastAPI, and wired it up. Took maybe 20 minutes. Then I started actually using it. The request: Request problem The first thing that got to me was the request: Request requirement. SlowAPI's decorator needs access to the request to extract the client IP or user ID, and the only way it can get that is if your route function accepts it as a parameter. So every rate-limited route ends up looking like this: @app.get ( " /items " ) @limiter.limit ( " 10/minute " ) async def get_items ( request : Request ): return await fetch_items () That request: Request is not doing anything. fetch_items() does not use it. It's there purely because SlowAPI needs it. Small thing, but it bothered me — I like function signatures that say exactly what they need, and this one was lying. The header injection problem I could live with that. The thing I could not live with was the header injection. Rate limit headers are genuinely useful — X-RateLimit-Remaining tells clients when to back off, Retry-After tells them how long to wait. Standard stuff. So I enabled SlowAPI's header injection and immediately hit a wall: every rate-limited route now had to return a Response object directly. Not a dict. Not a Pydantic model. A Response . The moment you enable header injection, SlowAPI expects to work with an actual response object, and if your route returns anything else it just breaks. So I was suddenly doing this: @app.get ( " /items " ) @limiter.limit ( " 10/minute " ) async def get_items ( request : Request , response : Response ): items = await fetch_items () return JSONResponse ( content = jsonable_encoder ( items )) Which is annoying because one of the things I actually like about FastAPI is that you declare a return type, FastAPI handles the serialization, and your OpenAPI schema just works. Sl
AI 资讯
Precision Medicine RAG: Building a Clinical Trial Search Engine with Hybrid Search and BGE-M3
In the world of Generative AI, there is a massive difference between asking for a "pancake recipe" and asking for "eligibility criteria for phase III immunotherapy trials." In specialized fields like healthcare, a standard vector search often fails because medical terminology is dense, specific, and unforgiving. 🏥 Today, we are building a High-Precision Medical RAG (Retrieval-Augmented Generation) engine. We will move beyond simple semantic search by implementing Hybrid Search (Dense + Sparse vectors) using the powerhouse BGE-M3 model, storing it in Qdrant , and fine-tuning the results with FlashRank . This approach ensures that technical medical terms (like EGFR L858R mutation ) aren't lost in the "vibe" of a vector space. Keywords: Hybrid Search , Medical RAG , BGE-M3 Embeddings , Qdrant Vector Database , Clinical Trial Retrieval . The Architecture: Why Hybrid Search? Traditional RAG relies on "Dense Vectors" (semantic meaning). However, in clinical trials, keywords matter. A patient searching for "Pembrolizumab" needs that exact drug, not just "something related to cancer." By using BGE-M3 , we get the best of both worlds: Dense Retrieval : Captures the context and intent. Sparse Retrieval (Lexical) : Captures specific keywords and medical codes. Reranking : Re-evaluates the top hits to ensure the most clinically relevant document is on top. graph TD A[User Query: Medical Case] --> B{BGE-M3 Encoder} B -->|Dense Vector| C[Qdrant Collection] B -->|Sparse Vector| C C --> D[Hybrid Search Results] D --> E[FlashRank Reranker] E --> F[Top K Relevant Documents] F --> G[LLM: Final Synthesis] G --> H[Actionable Clinical Insight] Prerequisites 🛠️ Before we dive in, make sure you have your environment ready: Qdrant : Our high-performance vector database. BGE-M3 : A state-of-the-art embedding model that supports dense, sparse, and multi-vector retrieval. FlashRank : An ultra-fast, lightweight reranking library. LangChain : To orchestrate our RAG pipeline. pip install qdrant-c
AI 资讯
Securing LLM Agent Teams: Inside NRT-Defense v0.4.0
Securing LLM Agent Teams: Inside NRT-Defense v0.4.0 Multi-turn autonomous LLM agents are expanding rapidly in safety-critical systems. However, a major vulnerability has been exposed by Lee et al. (2026) in the NRT-Bench paper : adaptive multi-turn attacks can exploit disjoint model vulnerabilities, causing a 8.7% to 12.1% loss of Critical Safety Functions (CSFs) . To solve this, I am open-sourcing NRT-Defense , an adaptive multi-turn defense framework designed to monitor agent sessions and reduce the attack success rate to <1% . The Threat: Context Drift and Disjoint Exploits Standard guardrails evaluate prompts in isolation (single-turn). Attackers leverage this by spreading an exploit across multiple conversational turns. Turn by turn, the context drifts until the agent team completely bypasses its safety containment. The NRT-Bench paper demonstrated this in a simulated nuclear power plant control room with 5 operator roles, 4 attack channels, and 6 critical safety functions. The results were alarming: Metric Value Attack success rate 8.7% — 12.1% Sessions analyzed 149 Models tested 4 frontier LLMs Vulnerability overlap Nearly disjoint The key finding: vulnerabilities are nearly disjoint across models . An attack that works against GPT-4 may not work against Claude. This means model diversity is itself a defense — but only if you can detect and respond to attacks in real-time. The Solution: 3-Step CMPE Defense nrt-defense neutralizes this threat through a continuous, multi-component pipeline: Per-Turn Message Analysis: Evaluates channel risk and turn-escalation metrics. Each message is scored for adversarial content using keyword detection, pattern matching, and channel-specific risk weights. Real-Time CSF Monitoring: Tracks 6 operational critical safety functions simultaneously. Risk accumulates over turns and triggers alerts when thresholds are breached. Context-Aware Misdirection Prompt Engineering (CMPE): When an anomaly is detected, instead of a blunt reject
AI 资讯
while Loop, break & continue, Lists (Creation, Mutability, Methods, List Comprehension)
📌 Key Concepts Overview Concept One-Line Definition while loop Repeats code as long as a condition is True while True Infinite loop — needs break to stop break Immediately exits the loop continue Skips current iteration, moves to next List Ordered, mutable collection — heterogeneous elements allowed List Comprehension One-line way to build a list using a loop + condition List Mutability Lists can be changed in place — id() stays the same 🔁 Part 1 — while Loop The 3 Components (Critical Pattern) # 1. Initialisation 2. Condition 3. Increment/Decrement a = 1 # 1. Initialisation while a <= 10 : # 2. Condition print ( ' Devops ' ) a += 1 # 3. Increment # Without increment → INFINITE LOOP (condition never becomes False) How it works: Condition is checked before each iteration. As soon as it's False , the loop stops. Miss the increment/decrement → infinite loop (a real production hazard — can hang a script or burn CPU). while — Practical Patterns # Countdown (decrement) a = 10 while a > 0 : print ( ' Devops ' ) a -= 1 # Sum of 1 to 20 total = 0 a = 1 while a <= 20 : total += a a += 1 print ( total ) # 210 # Product (factorial-style) of 1 to 20 product = 1 a = 1 while a <= 20 : product *= a a += 1 print ( product ) # Pattern using while + string repetition str1 = ' Devops ' i = 0 while i < len ( str1 ): print ( str1 [ i ] * ( i + 1 )) i += 1 # D # ee # vvv # oooo # ppppp # ssssss for vs while — When to Use Which Use for Use while You know the iterable / number of repetitions You don't know how many times — depends on a condition Looping over list, string, range Retry logic, polling, waiting for a state # DevOps: retry logic — classic while True use case max_attempts = 5 attempt = 0 while attempt < max_attempts : print ( f ' Attempt { attempt + 1 } : Connecting to server... ' ) # if connection succeeds: break attempt += 1 while True — Infinite Loop Pattern # Always True — runs forever until break is hit # Used for: retry logic, polling, menu-driven scripts, password validati
开源项目
🔥 unslothai / unsloth - Unsloth Studio is a web UI for training and running open mod
GitHub热门项目 | Unsloth Studio is a web UI for training and running open models like Gemma 4, Qwen3.6, DeepSeek, gpt-oss locally. | Stars: 66,943 | 116 stars today | 语言: Python
开源项目
🔥 microsoft / presidio - An open-source framework for detecting, redacting, masking,
GitHub热门项目 | An open-source framework for detecting, redacting, masking, and anonymizing sensitive data (PII) across text, images, and structured data. Supports NLP, pattern matching, and customizable pipelines. | Stars: 9,302 | 421 stars today | 语言: Python
开源项目
🔥 yt-dlp / yt-dlp - A feature-rich command-line audio/video downloader
GitHub热门项目 | A feature-rich command-line audio/video downloader | Stars: 171,966 | 341 stars today | 语言: Python
AI 资讯
Stop Competitors from Scraping Your Data! Building a Backend Defense for Your E-commerce Store
In the world of cross-border e-commerce, malicious bot scraping leading to Meta/Google Pixel pollution is a nightmare for every seller. When your store starts gaining traction, these fake traffic sources can "poison" your ad model, causing your ROAS to plummet. To combat this, I’ve developed a robust "Backend Data Isolation" architecture. The Core Defense Strategy Stop triggering ad conversion events directly from the frontend. Instead, build a "firewall" at the backend to ensure that only verified, high-quality conversion data is sent to your ad platforms. Technical Implementation By implementing server-side logic in Python, we can filter out bot requests effectively: def process_pixel_event ( request ): # Filter out bot signatures (User-Agent, IP analysis) if is_bot_signature ( request . headers [ ' User-Agent ' ]): return None # Send only high-quality data to ad platforms if is_real_customer ( request . session ): trigger_pixel_event ( request ) By leveraging this logic, we feed "private, high-quality data" to the AI. This allows the algorithm to learn only from genuine customer behaviors, creating an "immortal pixel" moat around your store. Learn More For a deep dive into full-scale anti-scraping deployments and how to leverage automated translation techniques to scale traffic in blue-ocean markets, check out my full technical guide: 👉 Read the Full Implementation & Troubleshooting Guide Here
AI 资讯
Access 40+ AI Providers with One API Key: Building with the Onlist SDK
If you've worked with multiple AI APIs, you know the pain: different auth flows, different SDKs, different billing dashboards, different rate limits. You end up with a providers/ folder full of wrapper code just to normalize the responses. Onlist solves this by putting 40+ AI providers behind a single OpenAI-compatible endpoint. One API key, one billing account, same chat.completions.create() call you already know. We just shipped official SDKs for Python and JavaScript/TypeScript, so I wanted to walk through what they look like in practice. The 30-Second Setup Python: pip install onlist from onlist import Onlist client = Onlist () # reads ONLIST_API_KEY from env response = client . chat . completions . create ( model = " openai/chatgpt-5.5 " , messages = [{ " role " : " user " , " content " : " Hello! " }], ) print ( response . choices [ 0 ]. message . content ) TypeScript: npm install @onlist/sdk import { Onlist } from " @onlist/sdk " ; const client = new Onlist (); const response = await client . chat . completions . create ({ model : " openai/chatgpt-5.5 " , messages : [{ role : " user " , content : " Hello! " }], }); console . log ( response . choices [ 0 ]. message . content ); That's it. No base URL to configure, no special headers to set. If you've used the openai package before, you already know how to use this. Why Not Just Use the OpenAI SDK Directly? You absolutely can. Onlist is fully OpenAI-compatible, so this works fine: from openai import OpenAI client = OpenAI ( base_url = " https://onlist.io/v1 " , api_key = " your-key " , ) The SDK adds three things on top of that: Default configuration. No base_url to remember. The ONLIST_API_KEY env var just works. Marketplace API. A .marketplace namespace for browsing models and providers programmatically. Proper User-Agent. Helps us debug issues when you reach out for support. If you're already using OpenAI or OpenRouter, switching takes one line: - from openai import OpenAI + from onlist import Onlist - clien
AI 资讯
Enterprise Design Patterns in Python: Repository & Unit of Work — Real-World E-Commerce Example
Enterprise Design Patterns in Python: Repository & Unit of Work 🐍🏗️ Series: Enterprise Application Architecture | Source: Fowler's EAA Catalog | Code: GitHub Repository 🧠 What Are Enterprise Design Patterns? Martin Fowler's Patterns of Enterprise Application Architecture (2002) is one of the most influential books in software engineering. It documents recurring architectural solutions — patterns — that solve common problems in enterprise systems: how to organize domain logic, how to talk to databases, how to handle transactions, and more. In this article, we'll explore two of the most powerful and widely-used patterns from that catalog: Pattern Category Core Purpose Repository Data Source Abstracts data access behind a collection-like interface Unit of Work Data Source Tracks object changes and commits them as a single transaction These two patterns work beautifully together — and you'll see exactly why with a real-world example. 🛒 The Problem: An E-Commerce Order System Imagine you're building a backend for an online store. When a customer places an order: A new Order is created Each Product 's stock is decremented A Payment record is registered If any of these steps fail midway, the entire operation should roll back — no partial state. This is exactly the problem the Unit of Work pattern solves, and the Repository pattern makes it all cleanly testable. 📁 Repository Pattern Definition "A Repository mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." — Martin Fowler, PoEAA The Repository acts as an in-memory collection of domain objects. Your business logic never knows if it's talking to PostgreSQL, SQLite, or even a mock list — it just calls .add() , .get() , .list() . Domain Model # models.py from dataclasses import dataclass , field from typing import List from uuid import uuid4 @dataclass class Product : id : str name : str price : float stock : int @dataclass class OrderItem : product_id : str qua
AI 资讯
The CFO's AI Playbook: 5 Finance Automations Every Indian Business Should Run in 2026
Over 60% of APAC finance leaders say AI-led automation is their top priority for 2026. For Indian businesses, that stat hides a quieter truth: most SMBs have no idea which automation to start with. They hear "AI for finance" and picture an enterprise suite with a six-figure licence fee. Wrong picture. I've built finance automations for CA firms, D2C brands, trading desks, family-run manufacturers, and a few fintech startups. The pattern is always the same. Five finance processes eat the most hours, hide the most errors, and respond best to a simple Python layer on top of whatever ledger you already use. This is the playbook. No enterprise suite. No subscriptions you don't need. Each automation is something I've shipped for real clients using Python, free APIs, and a ledger that's usually Tally or Zoho Books. 1. Bank Reconciliation — The Single Biggest Time Sink in Indian Finance Every finance team I meet has the same nightmare. Statements from three or four banks. Tally or Zoho on the other side. An Excel sheet in the middle. Eight hours a month — sometimes more — matching rows. A CA friend was losing two sleepless nights before every GST deadline on exactly this. We replaced it with a Python script that pulls statements from email attachments, categorizes transactions using keyword rules, cross-references entries with Tally, and flags only the mismatches in a clean Excel file. Eight hours dropped to fifteen minutes of review. "Tu 2 saal pehle kyu nahi mila?" (Why didn't I meet you two years ago?) If your team is still opening each bank statement manually, start here. It's the highest-ROI automation in Indian finance. I've written the full workflow in how a weekend Python script saved a CA firm 209 hours during ITR season . 2. Cash Application — Matching Payments to Invoices at Indian Speeds Globally, AI-driven cash application handles up to 90% of invoice matching without human touch. In India, it's harder — money arrives in more shapes than most tools expect: UPI,
AI 资讯
Python for Beginners — Part 2: Variables, Data Types & Numbers
Part 2 of a beginner-friendly series on learning Python from scratch. In Part 1 , we installed Python, wrote our first program, and learned the syntax rules that hold everything together. Now it's time to start storing and working with information — which means variables and data types. What is a Variable? A variable is a name that points to a value stored in memory. Think of it as a labeled container you can put something into, and refer back to later by name. name = " Ramesh " age = 25 Unlike many other languages, Python doesn't need you to declare a variable's type ahead of time. You just assign a value with = , and Python figures out the type on its own. This is called dynamic typing . x = 5 # x is an integer x = " hello " # now x is a string — totally legal in Python This flexibility is convenient, but it also means you need to be a little more careful — Python won't stop you from changing a variable's type halfway through your program, even if that wasn't your intention. Variable Naming Rules Python is strict about how variable names can look: Must start with a letter or an underscore ( _ ) — never a number. Can only contain letters, numbers, and underscores. Cannot be a Python keyword ( class , for , if , etc.). Are case-sensitive — age , Age , and AGE are three different variables. age = 25 # valid _age = 25 # valid age2 = 25 # valid 2 age = 25 # invalid — cannot start with a number my - age = 25 # invalid — hyphens aren't allowed Naming conventions Python's style guide (PEP 8) recommends snake_case for variable names — lowercase words separated by underscores: first_name = " Ramesh " total_score = 95 Assigning Multiple Variables Python lets you assign several variables in a single line, which keeps code compact and readable. # One value to multiple variables x = y = z = 10 # Multiple values to multiple variables name , age , city = " Ramesh " , 25 , " Chennai " Data Types in Python Every value in Python belongs to a data type, which determines what kind of
AI 资讯
The ₹0 Automation Stack: Enterprise-Grade Workflows Without Paying for SaaS
₹37,500 per month. That was the SaaS bill a Jaipur-based textile exporter was paying for automating invoices, GST reconciliation, and shipping notifications across three platforms. Three dashboards, three logins, three support tickets every time something broke. I replaced all of it with Python scripts running on a ₹500/month VPS. The recurring cost dropped to effectively zero — and the workflows actually became more reliable. This isn't a hypothetical framework. This is the exact stack I've deployed across 11 Indian businesses over the past 18 months, from CA firms filing ITR returns to stock traders screening 150+ equities before market open. Every tool in this stack is free. Every workflow runs in production today. Why Indian Businesses Overpay for Automation Most business owners discover automation through SaaS marketing. The pitch is compelling: drag-and-drop workflows, no coding required, instant results. What the pricing page doesn't tell you is that the "Starter" plan handles 100 tasks per month, and your GST reconciliation alone burns through that in three days. The real cost isn't the subscription — it's the upgrade treadmill. You start at ₹2,000/month, hit the task limit by week two, upgrade to ₹8,000/month, then discover that the webhook integration you need is locked behind the "Business" tier at ₹25,000/month. For businesses processing under 10,000 transactions monthly — which includes the vast majority of Indian SMBs, freelancers, and professional firms — a Python-based stack isn't just cheaper. It's more flexible, more transparent, and entirely under your control. The Stack: Seven Layers, Zero Recurring Cost Here's every component of the automation stack I deploy for clients. Each layer is free, battle-tested, and replaceable without rebuilding the entire system. Layer 1 — Logic & Scripting: Python 3.11+ The backbone of every automation. Handles API calls, data transformation, conditional logic, and error handling. Free forever, runs anywhere. Layer
AI 资讯
Python for Beginners — Part 1: Getting Started & Syntax
A beginner-friendly series on learning Python from scratch, one concept at a time. If you've ever wanted to learn programming but felt intimidated by curly braces, semicolons, and confusing syntax — Python is where you start breathing easy. It reads almost like English, and it's one of the most in-demand languages in the world today, used everywhere from web apps to data science to automation scripts. This is Part 1 of a beginner series that will take you from "what even is Python" to writing real, working programs. Let's begin. What is Python? Python is a general-purpose programming language created by Guido van Rossum and first released in 1991. It's popular because of three big reasons: It's beginner-friendly. The syntax is clean and close to natural language. It's versatile. You can build websites, automate tasks, analyze data, train machine learning models, or write small scripts — all with Python. It has a massive ecosystem. Thousands of ready-made libraries mean you rarely build things from scratch. Python runs on Windows, macOS, and Linux, and it's free and open source. Installing Python Most systems can run Python after a quick install: Go to python.org/downloads and grab the latest stable version. During installation on Windows, make sure to check "Add Python to PATH" — this saves you a lot of headaches later. Verify the install by opening your terminal (Command Prompt, PowerShell, or your Mac/Linux terminal) and typing: python --version If you see something like Python 3.13.0 , you're good to go. Tip: On some systems (especially macOS/Linux), you might need to type python3 instead of python . Your First Python Program Open a terminal, type python , hit Enter, and you'll land inside the Python interactive shell . Try this: print ( " Hello, World! " ) You should see: Hello, World! Congratulations — you just wrote your first Python program. print() is a built-in function that displays output on the screen. For anything beyond one-liners, you'll want to write
AI 资讯
I Built an AI That Turns 2 Hours of Compliance Paperwork Into 3 Minutes — Full Architecture Teardown
Financial advisors have a dirty secret: they spend almost half their working hours not advising anyone. The culprit? Compliance documentation. After every client meeting, advisors must document what was discussed, what was recommended, whether those recommendations were suitable, and whether they followed FINRA and SEC rules — all in a format their CRM can ingest. A 45-minute meeting routinely generates 2 hours of paperwork. I built an open-source tool that does it in about 3 minutes. Here's exactly how — every architectural decision, every trade-off, and every line of code that matters. The Problem Is More Specific Than You Think When I started talking to advisory firms, I expected "meetings take too long" or "we need better CRM software." Instead, every compliance officer said the same thing: "We're not worried about the notes. We're worried about what's NOT in the notes." The real pain isn't documentation speed — it's the compliance gap. If a client says "I can't afford to lose this money" and the advisor recommends an aggressive growth fund, that's a FINRA 2111 suitability violation. But if the note-taker (usually the advisor, writing from memory hours later) forgets that quote? No record of the red flag. This changed my entire system design. It's not a transcription tool with formatting. It's a compliance engine that listens for mismatches. Architecture Four-stage pipeline: Audio → Transcription → Structured Extraction → Compliance Check → CRM Note (Whisper) (Claude via (Rule engine) (Formatter) OpenRouter) Stack: Python/FastAPI + React frontend + Whisper (local) + Claude via OpenRouter Two key design choices: Whisper runs locally. Advisory meetings contain PII and legally privileged information. Sending audio to third-party APIs isn't optional for most firms — it's a regulatory non-starter. Compliance engine is NOT an LLM. You can't have a probabilistic system making deterministic compliance judgments. The compliance check uses hardcoded rules against structur
AI 资讯
Parsing and Rebuilding EPUB Files in Python: Lessons Learned from Building an AI Translation Service
How we extract, translate, and reconstruct entire ebooks with Python while preserving every detail At LectuLibre, we built a service that translates entire books using large language models. Our users upload EPUB files, and our backend pipeline parses them, extracts the text, sends it to an LLM for translation, and then rebuilds the EPUB with the translated content—all while preserving the original formatting, images, and metadata. This sounded straightforward until we looked inside a real EPUB. EPUB is essentially a ZIP file containing a structured set of XHTML, CSS, and XML files. The content.opf file defines the reading order (spine), metadata, and manifest. The toc.ncx holds the table of contents. The actual text lives in XHTML documents, often split per chapter. To translate a book, we needed to: 1) reliably parse the EPUB, 2) locate all translatable text, 3) send it chunk by chunk to the LLM, and 4) rebuild the EPUB with the translated text while keeping every byte of the formatting intact. The Problem with Off-the-Shelf Libraries We initially reached for ebooklib , the most popular Python library for EPUB manipulation. It worked great for simple EPUBs—until we threw a few hundred real-world files at it. We quickly hit issues: Metadata loss : ebooklib didn’t fully preserve custom metadata or namespace-prefixed properties in the OPF. Namespace handling : When modifying XHTML, it could strip or mangle xmlns attributes, breaking rendering on some devices. TOC and spine sync : After rebuilding, the table of contents and spine often got out of sync unless we manually repaired them. Large files : Processing a 200‑chapter book consumed surprising memory because ebooklib loaded everything at once. We could have used a heavyweight tool like Calibre’s command-line interface, but that introduced external dependencies and wasn’t as programmatically flexible. Instead, we decided to stick with ebooklib for high-level book structure and augment it with lxml for precise XML c