Metadata-Version: 2.4
Name: dl-doctor
Version: 0.2.0
Summary: Bilingual (Persian/English) doctor for deep-learning training: finds common mistakes, explains why and how to fix them. By Tirotir.com
Author: Tirotir
License-Expression: MIT
Project-URL: Homepage, https://tirotir.com
Project-URL: Documentation, https://github.com/worker2025/dl-doctor/blob/main/docs/GUIDE.fa.md
Project-URL: Changelog, https://github.com/worker2025/dl-doctor/blob/main/CHANGELOG.md
Project-URL: Book website, https://tirotir.ir
Project-URL: Repository, https://github.com/worker2025/dl-doctor
Project-URL: Issues, https://github.com/worker2025/dl-doctor/issues
Project-URL: Companion book, https://github.com/worker2025/DL_book
Keywords: deep-learning,training,diagnostics,debugging,persian,farsi,matplotlib,rtl,fairness,education,pytorch,keras,tirotir
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: English
Classifier: Natural Language :: Persian
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Provides-Extra: plots
Requires-Dist: matplotlib>=3.5; extra == "plots"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: matplotlib>=3.5; extra == "dev"
Dynamic: license-file

# dl-doctor

**A bilingual (Persian / English) doctor for deep-learning training.** *By [Tirotir.com](https://tirotir.com)*

`dl-doctor` reads your training curves, datasets, predictions, gradients and models and tells you what is
probably wrong, **why it happens and how to fix it**, in Persian and English: a learning rate that is too high,
overfitting, test-set leakage through normalisation, vanishing gradients, dead ReLUs, an inverted digit image,
a model left in training mode. It also writes shareable HTML reports and draws loss curves, confusion matrices
and group-rate charts with correctly joined right-to-left Persian text.

Built as a companion to the Persian book
*یادگیری عمیق؛ با پروژه‌های کاربردی برای مربیان و علاقه‌مندان کارگاه‌های هوش مصنوعی*
(Dr. Dariush Alipour and Dr. Minoosh Heidari); each finding points to the book chapter that covers the topic.
The library does **not** depend on the book and works with any PyTorch / Keras / NumPy workflow.

- Core dependency: NumPy only. PyTorch, Keras and matplotlib are optional and never imported unless you use them.
- Python 3.9+.
- 📘 **Full Persian guide:** [docs/GUIDE.fa.md](docs/GUIDE.fa.md) · 📋 all codes: [docs/CODES.md](docs/CODES.md) ·
  🧪 [examples/](examples/)

## Install

```bash
pip install dl-doctor            # diagnostics only
pip install "dl-doctor[plots]"   # + matplotlib plots
```

## Quick start

```python
import dldoctor as dd

history = {
    "loss":     [1.0, 0.8, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1],
    "val_loss": [1.0, 0.8, 0.7, 0.75, 0.8, 0.9, 1.0, 1.1],
}
report = dd.diagnose(history=history)
print(report)                    # English + Persian
report.to_text("fa")             # Persian only
report.save("report.html")       # shareable page with explanations and fixes
report.raise_for_errors()        # raise TrainingProblem if any ERROR finding

print(dd.explain("OVERFITTING_VAL_RISING"))   # why it happens, how to fix it
```

Everything at once; every argument is optional:

```python
report = dd.diagnose(
    history=history,                                   # dict, Keras History or HistoryRecorder
    X_train=X_train, y_train=y_train, X_test=X_test,   # leakage, scaling, class balance
    y_pred=y_pred, groups=gender,                      # statistical parity
    model=model, model_expect="eval",                  # PyTorch-like module
    grad_norms=dd.gradient_norms(model),               # vanishing / exploding gradients
    activations=hidden_output,                         # dead ReLUs
    digit_image=img28x28,                              # MNIST-style deployment check
)
```

In a hand-written loop:

```python
rec = dd.HistoryRecorder()
for epoch in range(epochs):
    ...
    rec.log(loss=train_loss, val_loss=val_loss, accuracy=train_acc, val_accuracy=val_acc)
print(rec.diagnose())
```

### What it checks (28 codes)

| Area | Finding codes |
|------|---------------|
| Training curves | `TRAIN_NONFINITE`, `LR_DIVERGING`, `LR_OSCILLATING`, `LR_STALLED`, `OVERFITTING_VAL_RISING`, `OVERFITTING_GAP`, `NO_VALIDATION_METRICS` |
| Network internals | `GRAD_VANISHING`, `GRAD_EXPLODING`, `DEAD_RELU` |
| Data | `DATA_NONFINITE`, `DATA_SPLIT_OVERLAP`, `NORM_FIT_ON_FULL_DATA`, `NORM_PER_SPLIT`, `DATA_UNSCALED`, `CLASS_IMBALANCE` |
| Fairness | `FAIRNESS_PARITY`, `FAIRNESS_OK` |
| Deployment | `DIGIT_SHAPE`, `DIGIT_BLANK`, `DIGIT_RANGE`, `DIGIT_BACKGROUND`, `DIGIT_SIZE`, `DIGIT_OFF_CENTER` |
| Frameworks | `TORCH_TRAIN_MODE`, `TORCH_EVAL_MODE_IN_TRAINING`, `TORCH_NONFINITE_PARAMS` |

Each `Finding` has `code`, `severity` (`INFO` / `WARNING` / `ERROR`), `message_fa`, `message_en`, `chapter`
and `details`. The checks are heuristics: a warning is a hint to look, not proof of a bug. Fairness output in
particular is one metric among several and never a verdict on its own.

## Persian plots

```python
from dldoctor.plots import plot_history, plot_confusion_matrix, plot_group_rates

plot_history(history, lang="fa", save="curves.png")
plot_confusion_matrix(y_true, y_pred, labels=["گربه", "سگ", "پرنده"], save="cm.png")
plot_group_rates({"الف": 0.80, "ب": 0.45}, save="rates.png")
```

Recent matplotlib releases join and reorder Arabic-script text themselves; `dl-doctor` detects this at run time.
On older releases it falls back to a built-in, dependency-free shaper (`dldoctor.shape_text`) that works for short
labels. Persian digits are used automatically. For the best look install a Persian font such as Vazirmatn;
otherwise DejaVu Sans is used.

## Command line

```bash
dldoctor check history.json            # or .csv; exit status 1 on ERROR (--fail-on warning|never)
dldoctor check history.json --lang fa --json
dldoctor report history.json --out report.html      # .html, .md or .json
dldoctor explain LR_DIVERGING          # why + how to fix, fa and en
dldoctor list                          # every code (add --md for the full reference)
dldoctor check-digit digit.npy         # a 28x28 image saved with numpy
dldoctor plot history.json --out curves.png
dldoctor demo
```

## Examples

| File | Shows |
|------|-------|
| `01_quickstart.py` | six common mistakes diagnosed in one call each |
| `02_numpy_mlp_from_scratch.py` | a tiny NumPy network trained four ways: clean, diverging, overfitting, dead ReLU |
| `03_data_checks.py` | leakage, wrong normalisation, duplicates, imbalance, unscaled pixels |
| `04_fairness_and_deployment.py` | statistical parity and digit-image deployment mistakes |
| `05_pytorch.py`, `06_keras.py` | framework loops (need torch / tensorflow) |
| `07_reports_plots_and_cli.py` | HTML/Markdown reports, `explain`, Persian plots, CLI |

## Limitations

- The PyTorch checks are duck-typed (`model.training`, `model.named_parameters()`, `param.grad`); they were tested
  with stand-in objects, not against every PyTorch release. Examples 05 and 06 need real torch / tensorflow and are
  not part of the automated tests.
- `check_split_overlap` compares rows bit-for-bit, so it finds exact duplicates only.
- Normalisation checks need at least 30 rows in each split and standardised (mean 0, std 1) data.

---

## فارسی

`dl-doctor` منحنی آموزش، داده‌ها، پیش‌بینی‌ها، گرادیان‌ها و مدل شما را بررسی می‌کند و به **فارسی و انگلیسی** می‌گوید
چه چیزی احتمالاً مشکل دارد، **چرا رخ می‌دهد و چطور درستش کنیم**: نرخ یادگیری بزرگ، بیش‌برازش، نشت داده در نرمال‌سازی، محو
گرادیان، ReLU مرده، تصویر وارونهٔ رقم دست‌نویس، یا مدلی که در حالت آموزش مانده است. گزارش HTML قابل اشتراک می‌سازد و
نمودارها (منحنی هزینه، ماتریس درهم‌ریختگی، نرخ گروه‌ها) را با متن فارسیِ درست رسم می‌کند.

هر یافته به فصل مربوط در کتاب «یادگیری عمیق؛ با پروژه‌های کاربردی برای مربیان و علاقه‌مندان کارگاه‌های هوش مصنوعی»
(دکتر داریوش علیپور – دکتر مینوش حیدری) ارجاع می‌دهد؛ ولی کتابخانه به کتاب وابسته نیست و با هر پروژهٔ PyTorch / Keras / NumPy
کار می‌کند.

📘 **راهنمای کامل فارسی:** [docs/GUIDE.fa.md](docs/GUIDE.fa.md)

```bash
pip install dl-doctor
pip install "dl-doctor[plots]"   # برای نمودارها
```

```python
import dldoctor as dd
گزارش = dd.diagnose(history={"loss": [...], "val_loss": [...]})
print(گزارش.to_text("fa"))                 # فقط فارسی
گزارش.save("report.html")                   # گزارش با توضیح و راه‌حل
print(dd.explain("LR_DIVERGING", "fa"))     # توضیح کامل یک کد
```

بررسی‌ها تشخیص‌های تجربی (heuristic) هستند؛ هشدار یعنی «نگاه کنید»، نه اثبات خطا. خروجی انصاف (fairness) فقط یکی از
چند معیار است و به‌تنهایی حکم نهایی نیست.

## Book, license and attribution

The **code** of this library is released under the MIT License (see `LICENSE`).

The companion **book** is a separate work licensed under
[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0). This repository contains only short, original
messages that point to chapter numbers; it does not reproduce the book's text, figures or code. If you reuse the
book itself, keep its attribution and update link:

- Authors: Dr. Dariush Alipour and Dr. Minoosh Heidari (انتشارات علیپور، تیروتیر), first edition, Aban 1405 (Nov 2026)
- Telegram: [@AI_and_Philosophy](https://t.me/AI_and_Philosophy)
- GitHub: <https://github.com/worker2025/DL_book> and <https://github.com/worker2025/>
- Web: <https://tirotir.ir>

Chapter numbers in findings refer to the first edition and may change in later editions.

---

*dl-doctor · By [Tirotir.com](https://tirotir.com)*
