اسکریپت پایتون ساخت فاکتور PDF فارسی از اکسل
با این پرامپت یک پروژه پایتون میسازی که فایل اکسل فاکتور را میخواند و PDF فارسی راستبهچپ با فونت内장شده، تاریخ شمسی، مالیات و شماره صفحه تولید میکند. مناسب فروشگاهها و فریلنسرهایی که فاکتور رسمی میخواهند.
You are a senior Python developer specialising in automated document generation and right-to-left (RTL) typography for Persian text. GOAL: Build a production-ready Python project that reads an Excel (.xlsx) or CSV file of invoice line items and generates polished, print-ready A4 PDF invoices in Persian with correct RTL rendering, an embedded Persian font, a Jalali (Shamsi) date, tax calculation, and page numbering. INPUT DATA: assume a file named 'invoices.xlsx' with the columns: invoice_id, invoice_date, seller_name, seller_phone, customer_name, customer_national_id, item_name, quantity, unit_price, discount_percent, tax_percent. Several rows may share the same invoice_id. TECHNICAL REQUIREMENTS: 1. Primary approach: a Jinja2 HTML template with RTL CSS rendered to PDF by WeasyPrint, embedding the Vazirmatn font from a local ./fonts folder so Persian letters render correctly on any machine. 2. Provide a fallback using reportlab + arabic-reshaper + python-bidi, and state clearly when each approach must be used. 3. Convert Gregorian dates to Jalali with jdatetime and print them in Persian digits; group rows by invoice_id so each invoice becomes its own file named '{invoice_id}_{customer_name}.pdf' inside ./output/. 4. Compute line totals, then subtotal, discount, tax (from config, default 9%), and grand total; format amounts with thousands separators and a configurable currency symbol (default 'تومان'). 5. Add a helper that converts the grand total into Persian words (e.g. 'دو میلیون و پانصد هزار تومان'). 6. CLI: python make_invoice.py --input invoices.xlsx --config config.json --out ./output ; defaults for seller details, logo path, tax rate and currency come from config.json. 7. Validation before generation: required columns present, no empty customer_name or item_name, quantity > 0, prices not negative, duplicate items merged, tax between 0 and 100. On failure print a clear Persian message and skip only the broken invoice, not the whole batch. 8. Layout: seller header with logo and contact row, customer block, itemised table with zebra striping, footer with terms and a signature area; when an invoice spills onto a second page the table header must repeat and page numbers must read 'صفحه X از Y'. CODE QUALITY: - Full type hints, docstrings, small single-purpose functions, no function longer than 40 lines. - Use pathlib, argparse, logging and pandas; no paid APIs, no cloud services, no shell=True anywhere, and escape all injected text with markupsafe before building HTML. - Include requirements.txt, a README.md with run instructions, a description of the expected invoices.xlsx structure, and a pytest file testing totals, Jalali conversion and validation errors. OUTPUT FORMAT: deliver the files one by one in separate code blocks (make_invoice.py, template.html, config.json, requirements.txt, test_make_invoice.py), then the exact terminal commands to run the project, then a short troubleshooting table for the 4 most common Persian PDF problems (disconnected letters, reversed text, missing font, wrong text direction). Finish with 3-5 bullet points explaining the trade-offs of the approach you chose.
کد پایتون برای تبدیل فایل CSV به JSON با اعتبارسنجی دادهها
این اسکریپت به کاربر اجازه میدهد فایل CSV را به JSON تبدیل کند و تمام ستونها را بهصورت صحیح اعتبارسنجی نماید؛ برای پردازش سریع دادههای تجاری.
You are a Python coding assistant. Write a Python script that reads a CSV file, validates each row's required fields (e.g., name, email), converts the data into a JSON array of objects, and saves the result to a new file. Include command‑line arguments for input and output paths, handle file‑not‑found and malformed‑row errors, use the csv and json standard libraries, and ensure UTF‑8 encoding for the output JSON file.
اسکریپت پایتون ساخت زیرنویس فارسی و انگلیسی برای ویدیوهای یوتیوب با Whisper
یک اسکریپت پایتون آماده که از لینک یوتیوب صدا را میگیرد، با Whisper زیرنویس فارسی میسازد، تایمبندیها را بر اساس سرعت مطالعه اصلاح میکند و فایل SRT/VTT و ویدیوی سابتیتلدار تحویل میدهد.
You are a senior Python engineer specialized in media automation, speech recognition and ffmpeg pipelines. Write production-ready code, not pseudocode. GOAL Build a single-file CLI tool named persian_subtitle.py that turns a YouTube URL (or a local media file) into broadcast-quality Persian subtitles, an optional English translation track, and a subtitled video. TECH STACK - Python 3.10+, type hints and dataclasses, argparse, pathlib, logging - yt-dlp for audio extraction, ffmpeg for audio conversion and burning subtitles - faster-whisper (large-v3, compute_type int8 on CPU / float16 on CUDA, vad_filter=True) with a JSON transcript cache - optional translation step behind an injected callable so the tool works with any MT provider (key read from environment variable, never hardcoded) FUNCTIONAL REQUIREMENTS 1. Input handling: accept a URL or local path, a --lang-source (default fa) and --lang-target (default en) pair, --model-size, --device, --output-dir and --burn-in flags. 2. Pipeline: download bestaudio with yt-dlp, convert to 16 kHz mono WAV via ffmpeg, run whisper with word_timestamps=True, cache raw segments to transcript.json and reuse on re-run. 3. Subtitle segmentation engine (the most important part): build cues from word timings using these rules — max 2 lines per cue, max 42 characters per line, reading speed <= 17 characters/second, minimum duration 1.2 s, maximum duration 7 s, minimum 80 ms gap between cues, no overlapping timestamps, split on Persian and English sentence/clause punctuation, merge very short fragments with neighbours, never break inside a number, Latin brand name or URL. 4. Persian text normalization: convert Arabic ي/ك/ة to Persian ی/ک/ه, normalize Arabic-Indic digits to Persian digits, collapse repeated spaces, trim filler words from a configurable list, and fix punctuation spacing so no space appears before ، ؛ ؟. 5. Output: write SRT and WebVTT in UTF-8 with BOM for legacy players, a bilingual mode that places English under Persian in the same cue, and a plain TXT transcript. Provide a summary report (cue count, average CPS, longest cue, total duration). 6. Burn-in: ffmpeg subprocess with the subtitles/ass filter, using an .ass override style with a Persian font (Vazirmatn), font size, primary/outline colour, outline and shadow width, bottom margin and alignment; make the style configurable and skip gracefully if the font is missing. 7. Engineering quality: ffmpeg/whisper availability checks with clear error messages, retry with exponential backoff on download failures, --dry-run mode, progress logging with percentages, clean temp-file cleanup, memory-safe batching for long videos, and a downloadable-content rights warning in the docstring. CONSTRAINTS - No global state, no hardcoded API keys or absolute paths, no shell=True. - Each segmentation function must be pure and unit-testable. - Explain every non-obvious constant in comments in one short line. - Keep the total file readable: modular functions, not one giant main(). OUTPUT FORMAT (in this order) 1. A short architecture note (max 150 words) explaining the data flow. 2. The complete code in one python block. 3. A requirements.txt block. 4. A usage section with 4 copy-paste commands: quick start, CUDA model, bilingual output, burn-in subtitles. 5. A flag reference table (flag, default, description). 6. A troubleshooting list for: ffmpeg not found, CUDA out of memory, whisper hallucinating repeated text in silent parts, and Persian glyphs rendering as boxes in the burned video.
اسکریپت پایتون برای استخراج قیمت روزانه از مدلهای املاک
یک پرامپت برای نوشتن اسکریپت پایتون که به صورت خودکار قیمتهای روزانه محصولات را از وبسایت مدلهای املاک استخراج میکند، با پشتیبانی از ذخیرهی دادهها در فایل CSV و ثبت لاگ.
You are a Python developer tasked with building an automated web scraper that extracts current product prices from the website "Modin-e-Online.com" (a fictional real estate listings site that also sells home goods). The user wants a script that runs daily via cron, stores the scraped prices in a CSV file, and includes error handling and logging. Inputs: - Source URL: https://www.modin-e-online.com/categories/home-goods - Output file: daily_prices.csv - Frequency: Daily (cron expression: "0 8 * * *") - Data points: product name, price, currency, timestamp of scrape Instructions: 1. Use the requests library to fetch the page with a realistic User-Agent header. 2. Parse HTML with BeautifulSoup, targeting elements with class "product-card". 3. For each product, extract: a. Product name (class "product-title") b. Price text (class "product-price") c. Currency symbol (if present) 4. Clean the price text: remove whitespace, commas, and convert to float (store original formatted price separately). 5. Append a timestamp (UTC) to each record. 6. Write all records to "daily_prices.csv" using csv.writer, ensuring headers are written only on the first run. 7. Implement try/except blocks to log any request or parsing errors to a file "scraper.log" using the logging module. 8. After scraping, print a summary: number of items scraped and the file path saved. 9. Include a main() function and guard with if __name__ == "__main__": to allow import. 10. Add comments explaining each section for maintainability. Output Format: Return the complete Python script as plain code, without any additional explanation or commentary.
اسکریپت پایتون دریافت زمان حرکت اتوبوس های تهران
اسکریپت پایتون را میسازید تا زمان حرکت اتوبوسهای تهران را از دادههای رسمی API شهر دریافت کند و به سامانه هماهنگی بدهد.
You are a senior Python backend engineer. Build a Python script that fetches real-time bus departure times from the Tehran City Transit open API for specified stop IDs and sends them to a Telegram chat. Use requests and python-dotenv. Accept environment variables BASE_URL, STOP_IDS, TELEGRAM_BOT_TOKEN, CHAT_ID. Implement functions fetch_departures, filter_next, send_telegram_message. Handle HTTP errors, timeouts, retries, logging. Return next departures sorted by time. Output should be a single Python file named tehran_bus_bot.py with runnable main. Do not use external database or paid APIs. Add basic rate limiting and graceful shutdown.
اسکریپت تحلیل دادههای اینترنت اشیاء و اعلان تغییرات غیرعادی
این پرامپت نحوهی نوشتن اسکریپت پایتون برای جمعآوری دادههای سنسور خانه از IoT، محاسبهی میانگین و اعلان مقادیر غیرعادی از طریق ایمیل را توضیح میدهد.
You are an expert Python developer. Write a script that reads temperature and humidity data from a JSON file (each entry: {"timestamp": "ISO8601", "temperature": float, "humidity": float}) every 5 minutes. Compute rolling average of the last 10 readings for each metric. If any metric deviates from its rolling average by more than 10%, send an email alert to admin@example.com with subject 'Anomaly Alert – Temperature/Humidity' and include the current value, timestamp, and deviation percentage. Use the smtplib library for SMTP (smtp.gmail.com, port 587, user: admin, password: <password>) and log all alerts to a CSV file. Include robust error handling and comments for each section.
اسکریپت پایتون همگامسازی موجودی فروشگاه با آمازون
اسکریپت پایتون برای همگامسازی موجودی فروشگاه آنلاین با آمازون و تولید فایل آماده.
You are a senior Python engineer. Build a Python script that syncs product inventory data from the Shopify REST API to Amazon FBA through CSV import. Fetch inventory levels, normalize SKUs, handle bundle mappings, generate an FBA inventory file, and validate the result. Use requests, pandas, and pydantic. Input is Shopify API credentials plus a product CSV. Output is an FBA inventory CSV and an error report JSON. Include retry logic, idempotency, logging, and a CLI. Return the complete script with configuration placeholders.
سند تایید پرداخت زرینپال با پایتون
کد پایتون برای تایید وبهوک درگاه زرینپال، ذخیره تراکنش در پایگاه داده و جلوگیری از ثبت تکراری.
You are a senior backend engineer specializing in fintech integrations and Iranian payment gateways. Write production-ready Python code using FastAPI to handle ZarinPal payment webhook callbacks. Requirements: 1. Define an async POST endpoint at /payment/zarinpal/webhook. 2. Accept JSON payload from ZarinPal containing at least: authority, status, amount, ref_id. 3. Verify the payment by calling ZarinPal verification endpoint: https://api.zarinpal.com/pg/v4/payment/verify.json with merchant_id and authority. 4. Use environment variables: ZARINPAL_MERCHANT_ID and DATABASE_URL. 5. If verification succeeds and status is OK, save the transaction to PostgreSQL using SQLAlchemy async ORM. 6. Implement idempotency: if the same authority or ref_id has already been processed, return HTTP 409 Conflict and do not create a duplicate record. 7. Return HTTP 200 for successful processing, HTTP 400 for invalid payload, and HTTP 409 for duplicate transactions. Provide: - Pydantic models for request and response validation. - SQLAlchemy async Transaction model with fields: id, authority, ref_id, amount, status, paid_at, raw_payload (JSON), created_at, updated_at. - FastAPI app with dependency for database session. - httpx client for calling ZarinPal API. - Logging statements and basic exception handling. - Comments explaining each step. - Placeholders instead of real merchant keys. Output a single-file Python script (main.py) ready to run with uvicorn, followed by a short bullet-point setup guide. Use English for all code, comments, and documentation.
اسکریپت پایتون برای مانیتورینگ قیمت محصولات و ارسال اعلان تخفیف
یک اسکریپت کامل پایتون برای خواندن خودکار قیمتهای یک سایت فروشگاهی و ارسال پیامک یا ایمیل در صورت کاهش قیمت. برای توسعهدهندگانی که قیمتگذاری هوشمند میکنند بسیار کاربردی است.
Write a modular Python script using `requests` and `BeautifulSoup` to scrape product prices from a specified e-commerce URL. The script should store the prices in a SQLite database and compare them with the latest scrape. If a price drop exceeds a defined threshold (e.g., 5%), the script should send an email alert using `smtplib`. Include robust error handling for network timeouts, SSL errors, and HTML structure changes. The configuration for URLs and thresholds should be managed via a simple JSON config file.
نوشتن کامپوننت ریاکت برای نمایش وضعیت تایپ در چت
کامپوننت ریاکتی با وضعیت تایپ زمان واقعی، کلاینتها را در جریان مشارکت در گفتگو مطلع میکند. برای برنامههای مکالمه مدرن بسیار مناسب است.
You are a senior front‑end engineer tasked with implementing a real‑time typing indicator for a chat interface built with React. The component should: - Accept the following props: isTyping (boolean), typingUser (string) (optional), and className (string) for styling. - Render a <span> element with a CSS class "typing-indicator" that shows "typing..." and optionally displays the typingUser's name. - Use React's useEffect to listen for changes in the isTyping prop and update the DOM accordingly with a smooth fade‑in/out animation. - Ensure the component is accessible: include an aria-live region (polite) that announces when someone starts or stops typing. - The component must be written in functional React (no class components) and follow best practices such as linting (ESLint), Prettier formatting, and be compatible with both Create‑React‑App and Vite projects. - Provide a complete code snippet including the component definition, a brief example of how to integrate it into a parent chat component, and suggested CSS keyframes for the typing animation. Deliver the final answer as a single code block containing the React component, integration example, and CSS styles.