今日已更新 213 条资讯 | 累计 20683 条内容
关于我们

标签:#Python

找到 623 篇相关文章

开发者

How I Made My First Dollar with Python Automation - A Practical Guide

This isn't a tutorial. It's real experience. Most articles about making money with Python are vague: "Learn Python to make money" (then what?) "Do data analysis freelancing" (how to get clients?) "Write web scrapers" (legal gray area) I'll share my actual path: building an Excel template generator with Python, listing it for sale, and earning my first dollar. Why This Direction My background: Know Python, but not expert Made some automation scripts No product design experience Want products (scalable) not services (time-for-money) The opportunity: Huge Excel template market (many 10k+ sales on Gumroad) Templates are static, hard to customize I can make a "template generator" for customization Technical feasibility: Python's openpyxl generates Excel programmatically JSON config is user-friendly ~300 lines of code The Product Not an Excel file. A Python script that generates Excel files . Users get: generator.py - generator code config.json - configuration README.md - documentation Workflow: Edit config.json → Run python generator.py → Get customized Excel Technical Implementation Core code is simple: from openpyxl import Workbook from openpyxl.styles import Font , PatternFill wb = Workbook () ws = wb . active # Header style header_fill = PatternFill ( start_color = ' 6366F1 ' , fill_type = ' solid ' ) header_font = Font ( bold = True , color = ' FFFFFF ' ) # Write header ws [ ' A1 ' ] = ' Project Name ' ws [ ' A1 ' ]. fill = header_fill ws [ ' A1 ' ]. font = header_font # Add dropdown from openpyxl.worksheet.datavalidation import DataValidation dv = DataValidation ( type = ' list ' , formula1 = '" In Progress,Completed,Paused "' ) ws . add_data_validation ( dv ) dv . add ( ' B2:B100 ' ) wb . save ( ' output.xlsx ' ) Loop to create sheets, set styles, add validation. Productization Process Step 1: MVP One module only (knowledge base) Test generation Use myself for a week Step 2: Expand Add 6 modules Add JavaScript version (using exceljs ) Improve docs Step 3: Package

2026-06-01 原文 →
开发者

How to Find a Prime Number in Python — A Thinking Journey

Introduction Understanding how to find prime numbers is one of the best ways to develop logical thinking in programming. It looks simple on the surface, but it teaches you how to break a problem into smaller steps, build a solution gradually, and then improve it into a clean and reusable structure. In this blog, we will not jump directly into code. Instead, we will start from basic thinking, slowly convert that thinking into logic, and finally refine it into a proper Python program using functions and loops. The goal is not just to find prime numbers, but to understand how programming logic is actually built in real development. 1. Understanding the Problem First Before writing anything in Python, we need to understand what a prime number actually means. A prime number is a number that: is greater than 1 has exactly two divisors: 1 and itself So the real question becomes: How do we check whether a number has any divisors other than 1 and itself? That is the core problem we are trying to solve. 2. Thinking Like a Human Before Coding Let’s take a number, for example 13. To check if 13 is prime, we naturally try dividing it by smaller numbers: 2 → does not divide 13 3 → does not divide 13 4 → does not divide 13 5 → does not divide 13 and so on If none of these numbers divide 13 completely, then 13 is prime. So the logic is simple: Try dividing the number by possible candidates and see if any divide it perfectly. 3. Turning Thinking into a Basic Algorithm From the above idea, we can form a basic structure: We need: a number to test a variable that moves through possible divisors a way to detect whether a divisor exists We start checking from 2 because every number is divisible by 1 anyway. We also do not need to check beyond half of the number, because a number cannot have a divisor greater than half (except itself). So the idea becomes: Start divisor from 2 Go up to number // 2 If any number divides it evenly, it is not prime 4. First Working Logic (Direct Implementati

2026-06-01 原文 →
AI 资讯

I read a multi-agent reasoning paper, built the Claude-native version, and measured everything

RecursiveMAS (arXiv 2604.25917) showed that agents sharing internal reasoning state outperform agents that share only final outputs. The average accuracy gain across benchmarks was 8.3 points. The mechanism: each agent passes not just its answer but the latent embeddings from its own reasoning process, and the next agent conditions on both. The paper is a good result. The catch is access. RecursiveMAS requires open-weight models with hidden states exposed at inference time. That rules out Claude, GPT-4o, and Gemini. I built a Claude-native version using the Anthropic extended thinking API. The core idea transfers: instead of passing latent vectors, pass the full thinking text. The paper calls it internal state sharing; the Claude version calls it thinking-block relay. The architecture problem Claude's extended thinking blocks carry an encrypted signature tied to the originating conversation. You cannot pass a signed thinking block into a different agent's messages array. The API rejects it. The workaround: extract the text from the thinking block and inject it as a regular user message. # Extract thinking text from Agent 1 thinking_text = next ( ( b . thinking for b in response . content if b . type == " thinking " ), "" ) # Inject into Agent 2 as regular context, not as a thinking block context = f " Prior agent reasoning: \n { thinking_text } " The signature does not transfer. The reasoning does. relay-structured: what I built first The first architecture was a Planner > Critic > Solver loop where each agent emits a compact mental model JSON instead of raw thinking text. Raw thinking at a 1024-token budget is often compressed and fragmented. The hypothesis was that 150 tokens of structured signal carries more information per token than 1024 tokens of compressed prose. The schema each agent emits: { "interpretation" : "how the agent read the problem" , "key_steps" : [ "step 1" , "step 2" ], "rejected_approaches" : [ "approach tried and discarded" ], "confidence" :

2026-06-01 原文 →
AI 资讯

SDXL Turbo for Pinterest at Scale: How I Cut NSFW False-Positives by 73% and Dodged Style-Copyright Strikes (Python + diffusers)

⚠️ この記事はアフィリエイト広告(プロモーション)を含みます。リンク先で発生した収益の一部が運営者に支払われますが、読者の購入価格には一切影響ありません。 By the end of this article you'll have two runnable Python scripts: a CLIP-based pre-filter that re-checks SDXL Turbo output before it ever hits Pinterest, and a prompt sanitizer that strips artist names + trademarked characters so you don't eat a DMCA. I ran this pipeline for 41 days, generated 6,180 images, and went from a 9.7% Pinterest rejection rate down to 2.6%. Here's exactly what broke and what fixed it. Why SDXL Turbo (1-step, ~0.3s on a 4090) beats SD 1.5 for Pinterest volume First, the conclusion: if you're mass-producing pins, SDXL Turbo's single-step guidance_scale=0.0 generation is the only thing that makes the unit economics work. On my RTX 4090 I clock 0.31s per 512x512 image with Turbo vs 4.8s for a 30-step SDXL base run. That's 15x. Over 6,180 images that's the difference between 32 minutes and 8.2 hours of GPU time. But Turbo has a nasty side effect nobody warns you about: because it's distilled and runs at low resolution by default, its built-in StableDiffusionXLPipeline safety checker (when enabled) throws far more false positives on perfectly benign images — beaches, lingerie-free fashion flatlays, even close-up food. In my first 600-image batch, 58 images came back as black squares from the NSFW checker. 51 of them were photos of latte art and knitted sweaters . So I ripped out the default checker and built my own two-stage gate. Stage 1: Replacing the diffusers safety_checker with a tunable CLIP gate in Python The default safety_checker in diffusers is a binary black box — you get a black image and zero signal about why . For a production loop you need a confidence score so you can set your own threshold. I use OpenCLIP's ViT-B-32 to score each output against a small set of NSFW concept prompts, then compare to a safe-concept baseline. This code actually runs (tested on diffusers==0.27.2 , open_clip_torch==2.24.0 ): import torch import open_clip from PIL import Ima

2026-06-01 原文 →
AI 资讯

Building Hermes Financial Agent: An Explainable AI Copilot for EGX Investors

Overview I built Hermes Financial Agent — an AI-powered financial assistant for investors in the Egyptian Exchange (EGX). The goal: not just calculate portfolio value, but explain risks in a transparent, auditable way. Features Real EGX market data via Yahoo Finance Portfolio tracking and valuation Daily financial reports Telegram-user portfolio isolation Cached quote fallback for resilience Explainable risk insights Explainable Risk Intelligence Unlike traditional trackers, Hermes surfaces: Portfolio concentration risk Stale market data exposure Quote coverage percentage Valuation gaps from unavailable data Users understand confidence level behind their valuation — not just the number. Technical Stack Hermes Agent framework Python GitHub Actions (automated smoke testing) Offline-safe quote fallback architecture Repository 🔗 GitHub Repository Future Roadmap News sentiment analysis Investment thesis tracking Market briefing generation Advanced financial reasoning agents hermeschallenge

2026-06-01 原文 →
AI 资讯

Notes on Federated Learning and Differential Privacy

Notes on Federated Learning and Differential Privacy 2026-05-31 · privacy-preserving ML Working notes on building federated learning (FL) from scratch, what actually breaks under Non-IID data, and how differential privacy (DP) and secure aggregation fit on top — including the honest negative results that the marketing slides leave out. They follow the implementation in federated-learning-lab (FedAvg / FedProx / SCAFFOLD, DP-SGD, secure aggregation; 33/33 tests, literature cross-validated). 1. What federated learning actually is The data never moves. Instead of pooling everyone's data on one server, each client trains locally and sends model updates to a server that aggregates them. The canonical loop ( FedAvg ) is: Server broadcasts the global model. Each client does a few local SGD epochs on its own data. Each client sends back its updated weights. Server averages the weights (weighted by client data size) → new global model. That's it. The elegance is that raw data stays on-device; the difficulty is that the clients' data distributions are not identical. 2. The Non-IID problem (where FedAvg starts to hurt) FedAvg implicitly assumes every client sees roughly the same distribution. Real clients don't — one hospital sees different cases than another, one phone's keyboard sees different language. Under Non-IID data, each client's local optimum pulls in a different direction, so averaging their updates produces client drift : the global model lands somewhere none of them wanted. Two well-known fixes, both implemented and measured in the lab: FedProx — add a proximal term that penalises drifting too far from the global model. Stabilises training when clients are heterogeneous. SCAFFOLD — track control variates (correction terms) that estimate and subtract the drift direction. More state to communicate, but corrects the bias FedProx only damps. The honest finding worth repeating: on a strongly Non-IID split (e.g. label-skewed MNIST), the fancy methods don't always beat p

2026-05-31 原文 →
AI 资讯

Google Ads Transparency Scraper: pull any competitor's ads for $1.20/1K

Quick answer: The Google Ads Transparency Center is a public registry of every ad Google runs — but it ships no API and no bulk export . To get the data programmatically you scrape it. A Google Ads Transparency scraper sends the same RPC call the website uses and returns every ad creative for an advertiser as structured JSON. The Apify Actor below does it for $0.0012 per ad (~$1.20 per 1,000), with the TLS fingerprinting, proxy rotation, and pagination handled for you. Google's Ads Transparency Center is one of the most underused datasets in marketing. Launched in 2023 under the EU Digital Services Act and parallel US pressure, it indexes every ad campaign currently running on Search, YouTube, Display, Shopping, Maps, and Play — keyed by advertiser. Google's own counter lists 300,000+ active creatives for a brand like Nike . For your nearest competitor, it's usually 50–500. The catch: there's no download button. Just an interactive UI that paginates 40 creatives at a time. If you want this as a CSV — for a competitor sweep, a trademark audit, or a RAG corpus — you have to extract it yourself. Here's what that actually takes, and how I shortened it to one API call. What is the Google Ads Transparency Center? 🔎 The Google Ads Transparency Center is a public, Google-operated registry that shows the ad creatives any verified advertiser is running, the date range each ad was shown, and roughly where. Google built it to comply with ad-disclosure regulation, so the data is public by design — you're reading the same registry a regulator would. What it gives you per advertiser: Every ad creative currently or recently live (text, image, video) The landing domain each ad clicks through to First-shown / last-shown timestamps and a rough impression count A deep link to each creative inside the Transparency Center What it does not give you: a search-by-keyword mode, region-filtered results from the server, or — crucially — an API. Does the Google Ads Transparency Center have an A

2026-05-31 原文 →
AI 资讯

[Imposter syndrome] Back to the beginning (DevSecOps path)

I’ve been writing my project - Python port scanner for 9 months now. You might be wondering, “Why is it taking so long?” Most of the time was spent figuring out how raw sockets work, how to write a function for manually assembling a packet, calculating the checksum, packing the IP packet bytes, the TCP header, the pseudo-header using struct.pack, sending the packet, and how SYN scanning works. Why did I decide to take such a complicated route instead of just using Scapy? I’m a principled person and have a very exhausting yet useful skill—understanding everything. That’s how I got acquainted with big-endian, or “network byte order.” I won’t go into the details of big-endian logic, to be honest, I’m already mentally exhausted It took several evenings and nights to analyze and understand the principles—watching videos, reading RFCs, and looking at GitHub code (which I didn’t understand)—but what bothered me most was that I had to ask gemini for an explanation. As I mentioned above, I’m very principled; I can’t just copy code without understanding it, so I ask gemini for a prompt like this: “Don’t write the code for me. If I end up asking you for an example because I’m tired, explain it line by line.” Yesterday I realized I don’t fully understand Python (basics)—I don’t remember REPL—so I went to ask Gemini for advice; I don’t have anyone competent who could help me with advice. I’m not very sociable, and the only thing that’s interested me for the last four years is IT. I used to make music. Lately, something strange has been going on with my health, the day before yesterday I woke up because of a nosebleed; this has happened before, but on a larger scale. I stopped working on the scanner yesterday and decided to try writing a backup script in Python. I found an article and jotted down in Obsidian what the project should and shouldn’t do. Previously, the project used Docker, Prometheus, and Grafana. My questions: Am I a good developer, and am I even one at all? Should

2026-05-31 原文 →
AI 资讯

I built a RAG pipeline from scratch — no LangChain, just FastAPI + FAISS

Most RAG tutorials I found were either "pip install langchain and you're done" or 50-page academic papers. I wanted something in between — a pipeline I could actually explain in an interview, where I understood every line. So I built one from scratch. No LangChain, no LlamaIndex, no frameworks. Just FastAPI, FAISS, sentence-transformers, and an LLM API. Here's what I built, what worked, and what broke. The architecture PDF --> extract text (pypdf) --> chunk (500 char, 50 overlap) --> embed (MiniLM-L6-v2) | v question --> embed --> FAISS top-k search --> build prompt with chunks --> LLM --> answer + sources Five Python files, ~300 lines total: File Responsibility main.py FastAPI app, 3 endpoints, prompt engineering pdf_loader.py PDF text extraction via pypdf rag.py Chunking + embedding store.py FAISS vector store wrapper llm.py Swappable LLM client (Groq / OpenAI / Anthropic) How the upload works When you POST a PDF to /upload , three things happen: 1. Text extraction — pypdf reads each page and returns the raw text. Pages with no extractable text (scanned images) are skipped. 2. Chunking — each page is split into ~500-character chunks with 50 characters of overlap. The overlap prevents losing context at chunk boundaries. CHUNK_SIZE = 500 CHUNK_OVERLAP = 50 def chunk_pages ( pages ): chunks = [] chunk_id = 0 for text , page_num in pages : start = 0 while start < len ( text ): end = min ( start + CHUNK_SIZE , len ( text )) chunk_text = text [ start : end ]. strip () if chunk_text : chunks . append ( Chunk ( chunk_id = chunk_id , text = chunk_text , page = page_num )) chunk_id += 1 if end == len ( text ): break start = end - CHUNK_OVERLAP return chunks 3. Embedding — each chunk is embedded into a 384-dimensional vector using all-MiniLM-L6-v2 . This runs locally on CPU, no API call needed. Vectors are normalized so we can use inner product as cosine similarity. def embed_texts ( texts ): model = get_embed_model () # lazy-loaded singleton vectors = model . encode ( texts

2026-05-31 原文 →
AI 资讯

Local-first: a Model on Your Own Machine, Zero Cloud

This is the concrete, runnable walkthrough for Post 1 of the Portway series . The goal: stand up a single model behind an OpenAI-compatible endpoint on hardware you already own, call it from the official OpenAI SDK, and internalize the stateless contract. Everything here runs locally for $0. What this post covers A demo.py script with two blocks: Round-trip — one chat call via the OpenAI SDK, printing the content and the usage object. Stateless proof — the same final question sent as a 1-turn message and as the last turn of a 5-turn fabricated history; both prompt_tokens values are printed alongside an explanation of the delta. Engine choice on this machine Apple Silicon Mac, 48 GB unified memory, Ollama already installed. The demo uses Ollama's OpenAI-compatible endpoint at http://localhost:11434/v1 and the gpt-oss:20b model (~14 GB). The wider Portway series uses llama.cpp on Mac (Ollama is called out as problematic for Qwen3.5 in Post 2). For Post 1 — one model, prove the contract — Ollama is fine and already on the box. Model options by available RAM The demo script works with any Ollama-served model — just substitute the model name in demo.py . The table below covers machines from 9 GB unified memory upward. Model Pull command Approx size Min RAM Notes llama3.2:3b ollama pull llama3.2:3b ~2 GB 8 GB Fastest; good for testing the contract gemma3:4b ollama pull gemma3:4b ~3 GB 8 GB Google; solid instruction-following mistral:7b ollama pull mistral:7b ~4.1 GB 8 GB Classic 7B baseline llama3.1:8b ollama pull llama3.1:8b ~4.7 GB 9 GB Best quality under 10 GB qwen2.5:7b ollama pull qwen2.5:7b ~4.4 GB 9 GB Strong at instruction + reasoning gpt-oss:20b ollama pull gpt-oss:20b ~14 GB 24 GB Used in this post's sample output On a 9 GB machine, replace gpt-oss:20b in demo.py with llama3.1:8b or qwen2.5:7b — the contract demonstration is identical. Prerequisites Ollama running locally ( curl -s http://localhost:11434/api/tags should return JSON) uv installed ( uv --version )

2026-05-31 原文 →
AI 资讯

BAIXAR VÍDEO DO YOUTUBE

Criei um gerenciador de downloads desktop em Python e quero feedback da comunidade! O PyFlowDownloader é um app desktop feito com Python + PySide6 que usa yt-dlp para baixar vídeos e áudios de forma assíncrona do youtube. Algumas coisas que ele já faz: Fila de downloads com progresso em tempo real Cancelamento de downloads ativos ou pendentes Suporte a MP4 e MP3, de 144p até 1080p Histórico com exportação para CSV Interface desktop com tema visual via QSS Build para Windows via PyInstaller + pipeline de release no GitHub Actions Está na versão v0.3.0 e ainda tem muito espaço pra crescer. Repositório: https://github.com/Vinny00101/PyFlowDownloader Se você puder **testar e deixar sua opinião nos comentários, ficaria muito grato! Quer saber: O que achou da experiência de uso? Algum bug que encontrou? O que você adicionaria ou melhoraria no projeto? Todo feedback é bem-vindo!

2026-05-30 原文 →
AI 资讯

Quark's Outlines: Python User-defined Functions

Quark’s Outlines: Python User-Defined Functions Overview, Historical Timeline, Problems & Solutions An Overview of Python User-Defined Functions What is a Python user-defined function? You can define your own function in Python using the def keyword. A Python user-defined function is made when you write a def block in your code. When Python runs this block, it creates a function object. A function object has special parts. These include its name, its list of default values, and its code. It also keeps a link to the global names from the file where it was made. You can use this object to call the function later with any valid input. Python lets you create named function objects with the def keyword. def greet ( name = " friend " ): return " Hello, " + name print ( greet ()) print ( greet ( " Mike " )) # prints: # Hello, friend # Hello, Mike The function greet is now a user-defined function. Python stores its name, code, and default values for later use. What are the special parts of a Python function? A Python function holds many facts about itself. These are called attributes. For example, __name__ holds the function name. __defaults__ is a tuple of default values. __globals__ holds the global names it can see. __code__ is a special object that stores the function’s bytecode. Python functions store their details in special attributes. def square ( x = 2 ): return x * x print ( square . __name__ ) print ( square . __defaults__ ) print ( square . __code__ . co_varnames ) # prints: # square # (2,) # ('x',) These parts let Python understand and run your function later. A Historical Timeline of Python User-Defined Functions Where do Python’s user-defined functions come from? User-defined functions in Python build on ideas from earlier languages. They let you name blocks of code and reuse them. Over time, Python added new parts to function objects—like closures, default values, and metadata—to make them more powerful. People designed ways to name and reuse logic 1958 — Fu

2026-05-30 原文 →