From a7a13a606cff0ebde2574a28340710f7161b2d02 Mon Sep 17 00:00:00 2001 From: loonghao Date: Wed, 14 Oct 2026 04:36:22 +0800 Subject: [PATCH] docs: baseline docstring rules and generate llms.txt in CI Enable ruff's D rules with the existing docstring debt recorded as a per-directory baseline, so CI stays green on the current tree while new docstring debt fails immediately. Each baseline entry records its finding count; deleting a rule from an entry makes that tier's debt fail until it is fixed. Add scripts/generate_llms.py plus an llms-txt job that runs ahead of release-please and opens a pull request when the generated llms.txt or llms-full.txt differ from what is committed. The job is non-blocking: a failure reports red but does not hold the release. Configuration and documentation only; no packaging or lockfile changes. --- .github/workflows/release.yml | 58 +- llms-full.txt | 2147 +++++++++++++++++++++++++++++++++ llms.txt | 60 + pyproject.toml | 39 +- scripts/generate_llms.py | 417 +++++++ 5 files changed, 2716 insertions(+), 5 deletions(-) create mode 100644 llms-full.txt create mode 100644 llms.txt create mode 100644 scripts/generate_llms.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b96e06ea..c8d0d114 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -175,10 +175,64 @@ jobs: sys.exit(main()) PY + # ── llms.txt / llms-full.txt — regenerate before the release is cut ─────── + # Generated files, never hand-edited. Runs ahead of release-please so the + # version it stamps into llms.txt is the one about to be released. When the + # result differs from what is committed it opens (or updates) its own PR + # instead of pushing to main, so the content is reviewable like any other + # change and never silently rewrites the release branch. + # + # Non-blocking by design: `release-please` uses `always()` below, so a failure + # here reports red but does not hold the release hostage. The ordering is what + # matters, not the gate. + llms-txt: + needs: [preflight] + runs-on: ubuntu-latest + permissions: + contents: write # push the generation branch + pull-requests: write # open/update the PR + steps: + - uses: actions/checkout@v6 + with: + # fetch-depth 0: the generator stamps the version with + # `git describe --tags`, which needs the tag history. + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Regenerate llms.txt and llms-full.txt + run: python scripts/generate_llms.py + + # No-op when the output already matches what is committed: the action + # skips PR creation entirely when the branch has no diff, which is what + # keeps this from opening an empty PR on every push to main. + - name: Open a pull request when the generated files changed + uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8 + with: + token: ${{ secrets.GITHUB_TOKEN }} + branch: docs/update-llms-txt + title: "docs: regenerate llms.txt and llms-full.txt" + commit-message: "docs: regenerate llms.txt and llms-full.txt" + body: | + Automated regeneration by the `llms-txt` job in the Release workflow. + + `scripts/generate_llms.py` produced output that differs from what is + committed, which means a source it reads (README, `examples/`, or the + package version) changed. Review the diff and merge; no code is + affected. + + To regenerate locally: `python scripts/generate_llms.py`. + delete-branch: true + # ── Release Please — creates/updates the release PR, then the release ───── release-please: - needs: [preflight] - if: needs.preflight.outputs.releasable == 'true' + needs: [preflight, llms-txt] + # `always()` keeps a failed llms regeneration from blocking the release; the + # job above only orders itself ahead of this one, it does not gate it. + if: always() && needs.preflight.outputs.releasable == 'true' runs-on: ubuntu-latest permissions: contents: write # tag + GitHub Release diff --git a/llms-full.txt b/llms-full.txt new file mode 100644 index 00000000..2815d229 --- /dev/null +++ b/llms-full.txt @@ -0,0 +1,2147 @@ +# photoshop-python-api — full reference + +Version: 0.25.0 +Source: https://github.com/loonghao/photoshop-python-api +Documentation: https://photoshop-python-api.readthedocs.io/en/master/ + +This file concatenates the repository's documentation and example code so +it can be consumed in a single request. It is generated by +`scripts/generate_llms.py`; edit the sources, not this file. + +--- + +## README + +

Python API for Photoshop.

+

⚠️ Only for Windows platform !

+ +

The example above was created with Photoshop Python API. Check it out at https://loonghao.github.io/photoshop-python-api/examples.

+ +Has been tested and used Photoshop version: + +| Photoshop Version | Supported | +|-------------------| ------------------ | +| 2025 | ✅ | +| 2024 | ✅ | +| 2023 | ✅ | +| 2022 | ✅ | +| 2021 | ✅ | +| 2020 | ✅ | +| cc2019 | ✅ | +| cc2018 | ✅ | +| cc2017 | ✅ | + +Installing +---------- +You can install via pip. + +```cmd +pip install photoshop_python_api +``` + +Since it uses COM (Component Object Model) connect Photoshop, it can be used +in any DCC software with a python interpreter. + +Hello World +----------- + +```python + +import photoshop.api as ps +app = ps.Application() +doc = app.documents.add() +new_doc = doc.artLayers.add() +text_color = ps.SolidColor() +text_color.rgb.red = 0 +text_color.rgb.green = 255 +text_color.rgb.blue = 0 +new_text_layer = new_doc +new_text_layer.kind = ps.LayerKind.TextLayer +new_text_layer.textItem.contents = 'Hello, World!' +new_text_layer.textItem.position = [160, 167] +new_text_layer.textItem.size = 40 +new_text_layer.textItem.color = text_color +options = ps.JPEGSaveOptions(quality=5) +# # save to jpg +jpg = 'd:/hello_world.jpg' +doc.saveAs(jpg, options, asCopy=True) +app.doJavaScript(f'alert("save to jpg: {jpg}")') + +``` +![demo](https://i.imgur.com/25TrzbV.gif) + +Photoshop Session +----------------- +Use it as context. + +```python + +from photoshop import Session + +with Session(action="new_document") as ps: + doc = ps.active_document + text_color = ps.SolidColor() + text_color.rgb.green = 255 + new_text_layer = doc.artLayers.add() + new_text_layer.kind = ps.LayerKind.TextLayer + new_text_layer.textItem.contents = 'Hello, World!' + new_text_layer.textItem.position = [160, 167] + new_text_layer.textItem.size = 40 + new_text_layer.textItem.color = text_color + options = ps.JPEGSaveOptions(quality=5) + jpg = 'd:/hello_world.jpg' + doc.saveAs(jpg, options, asCopy=True) + ps.app.doJavaScript(f'alert("save to jpg: {jpg}")') + +``` + +# Repobeats analytics +![Repobeats analytics](https://repobeats.axiom.co/api/embed/0f4ab02065b94983fc95677c6587a61ce5fa8397.svg "Repobeats analytics image") + +how to get Photoshop program ID +------------------------------- +```PS> +Get-ChildItem "HKLM:\SOFTWARE\Classes" | + ?{ ($_.PSChildName -match "^[a-z]+\.[a-z]+(\.\d+)?$") -and ($_.GetSubKeyNames() -contains "CLSID") } | + ?{ $_.PSChildName -match "Photoshop.Application" } | ft PSChildName +``` +![get_program_id](https://i.imgur.com/UwPN7qq.png) + +[How to get a list of COM objects from the registry](https://rakhesh.com/powershell/how-to-get-a-list-of-com-objects-from-the-registry/) + +Useful links +------------ +- https://theiviaxx.github.io/photoshop-docs/Photoshop/ +- http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-javascript-ref-2015.pdf +- https://github.com/lohriialo/photoshop-scripting-python +- https://www.adobe.com/devnet/photoshop/scripting.html +- https://www.youtube.com/playlist?list=PLUEniN8BpU8-Qmjyv3zyWaNvDYwJOJZ4m +- http://yearbook.github.io/esdocs/#/Photoshop/Application +- http://www.shining-lucy.com/wiki/page.php?id=appwiki:photoshop:ps_script +- http://www.tonton-pixel.com/wp-content/uploads/DecisionTable.pdf +- http://jongware.mit.edu/pscs5js_html/psjscs5/pc_Application.html +- https://indd.adobe.com/view/a0207571-ff5b-4bbf-a540-07079bd21d75 +- http://shining-lucy.com/wiki/page.php?id=appwiki:photoshop:ps_script +- http://web.archive.org/web/20140121053819/http://www.pcpix.com/Photoshop/char.html +- http://www.tonton-pixel.com/scripts/utility-scripts/get-equivalent-id-code/index.html +- https://github.com/Adobe-CEP/CEP-Resources/tree/master/Documentation/Product%20specific%20Documentation/Photoshop%20Scripting +- https://github.com/Adobe-CEP/Samples/tree/master/PhotoshopEvents +- https://evanmccall.wordpress.com/2015/03/09/how-to-develop-photoshop-tools-in-python + +## 🛠️ Development Guide + +Welcome to the development guide for the Photoshop Python API project! This section outlines our development practices and standards to ensure code quality and consistency. + +### 📋 Quick Start for Contributors + +```bash +# Clone the repository +git clone https://github.com/loonghao/photoshop-python-api.git +cd photoshop-python-api + +# Install dependencies with Poetry +poetry install + +# Install pre-commit hooks +pre-commit install + +# Run tests +pytest +``` + +### 🎨 Code Style & Quality + +We maintain high code quality standards through automated tools and consistent style guidelines: + +- **Style Guide**: We follow the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html) with project-specific adjustments: + - Line length: 120 characters max + - Docstrings: Google style format + - Quotes: Double quotes preferred + +- **Quality Tools**: + - [Ruff](https://docs.astral.sh/ruff/) - Linting, formatting, and import organization + - [pre-commit](https://pre-commit.com/) - Automated checks before commits + +### 🔄 Git Workflow + +We use a structured workflow to maintain a clean and organized repository: + +- **Commit Messages**: Follow [Conventional Commits](https://www.conventionalcommits.org/) format + + ```text + (): + + [optional body] + + [optional footer(s)] + ``` + + Common types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` + +- **Branching Strategy**: + - Main branch: `main` - Always stable and deployable + - Feature branches: `feature/` + - Bug fixes: `fix/` + - Documentation: `docs/` + +### 🧪 Testing + +We value thorough testing to ensure reliability: + +- **Framework**: We use `pytest` for all tests +- **Coverage**: Aim for high test coverage on new features +- **Run Tests**: `pytest` or `poetry run pytest` + +### 📦 Development Environment + +- **Python Versions**: We support Python 3.10+ (see `pyproject.toml` for specifics) +- **Dependency Management**: [Poetry](https://python-poetry.org/) for consistent environments +- **Virtual Environment**: Poetry automatically creates and manages virtual environments + +### 🤝 Contributing Process + +1. **Fork & Clone**: Fork the repository and clone your fork +2. **Branch**: Create a feature branch with a descriptive name +3. **Develop**: Make your changes following our code style guidelines +4. **Test**: Ensure all tests pass and add new tests for new features +5. **Commit**: Use conventional commit format for clear history +6. **Push & PR**: Push your branch and create a Pull Request +7. **Review**: Address any feedback from code reviews +8. **Merge**: Once approved, your PR will be merged + +Thank you for contributing to the Photoshop Python API project! 🎉 + +### Development Notes + +One way to view the COM API structure is to use Visual Studio. + +1. Install Visual Studio with the .NET desktop development workload +2. Open Visual Studio +3. Choose View -> Object Browser +4. In the Object Browser from the Browse dropdown choose *Edit Custom Component Set...* +5. In the Edit Custom Component Set window's COM tab add Photoshop's Object and Type libraries +6. After pressing OK the libraries should show up in the Object Browser + +If the libraries aren't visible in the COM tab make sure you have the .NET desktop development workload installed. Other things you may try are running Photoshop once as administrator and reinstalling Photoshop and/or your PC. The object library is defined usually in */your/path/to/Adobe Photoshop \/Required/Plug-ins/Extensions/ScriptingSupport.8li* + +The [VBS reference 2020](https://github.com/Adobe-CEP/CEP-Resources/blob/master/Documentation/Product%20specific%20Documentation/Photoshop%20Scripting/photoshop-vbs-ref-2020.pdf) is also quite trustworthy, since Adobe isn't actively developing the COM API anymore. + + +--- + +--- + +## Contents + +- [Getting started](https://github.com/loonghao/photoshop-python-api/blob/main/README.md) — installation, requirements and supported Photoshop versions +- [API reference](https://photoshop-python-api.readthedocs.io/en/master/) — generated reference for every wrapper class +- [Examples](https://github.com/loonghao/photoshop-python-api/tree/main/examples) — 59 runnable scripts covering common tasks +- [Documentation source](https://github.com/loonghao/photoshop-python-api/tree/main/docs) — the MkDocs site sources + +--- + +## Examples + +Each example is a standalone script. Constants come from `photoshop.api.enumerations` and classes from `photoshop.api`. + +### _psd_files.py + + psd files + +```python +# Import built-in modules +import os + + +def get_psd_files(): + files = {} + this_root = os.path.dirname(__file__) + file_root = os.path.join(this_root, "files") + for file_name in os.listdir(file_root): + files[file_name] = os.path.join(file_root, file_name) + return files +``` + +### active_layer.py + +Example of working with active layers in Photoshop. + +```python +"""Example of working with active layers in Photoshop. + +This example demonstrates how to: +1. Get and set the active layer in a document +2. Create new art layers +3. Manage layer names and properties + +The script will: +- Create a new document if none exists +- Add a new art layer if document has less than 2 layers +- Display the current active layer name +- Create a new layer and rename it +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Get or create a document + if len(ps.app.documents) < 1: + docRef = ps.app.documents.add() + else: + docRef = ps.app.activeDocument + + # Ensure we have at least 2 layers + if len(docRef.layers) < 2: + docRef.artLayers.add() + + # Display current active layer name + print(docRef.activeLayer.name) + + # Create and rename a new layer + new_layer = docRef.artLayers.add() + print(new_layer.name) + new_layer.name = "test" +``` + +### add_metadata.py + +Add metadata to current active document. + +```python +"""Add metadata to current active document.""" + + +from __future__ import annotations +# Import built-in modules +import os + +# Import local modules +from photoshop import Session + + +with Session(action="new_document") as ps: + doc = ps.active_document + doc.info.author = os.getenv("USERNAME") + doc.info.provinceState = "Beijing" + doc.info.title = "My Demo" + print("Print all metadata of current active document.") + print(doc.info) +``` + +### add_slate.py + +Add slate information dynamically. + +```python +"""Add slate information dynamically. + +- Open template. +- Update info. +- Save as jpg. +- Close current document. + +""" + + +from __future__ import annotations +# Import built-in modules +import os + +from datetime import datetime +from tempfile import mkdtemp + +# Import local modules +import examples._psd_files as psd # Import from examples. + +from photoshop import Session + + +PSD_FILE = psd.get_psd_files() +slate_template = PSD_FILE["slate_template.psd"] +with Session(slate_template, action="open", auto_close=True) as ps: + layer_set = ps.active_document.layerSets.getByName("template") + + data = { + "project name": "test_project", + "datetime": datetime.today().strftime("%Y-%m-%d"), + } + for layer in layer_set.layers: + if layer.kind == ps.LayerKind.TextLayer: + layer.textItem.contents = data[layer.textItem.contents.strip()] + + jpg_file = os.path.join(mkdtemp("photoshop-python-api"), "slate.jpg") + ps.active_document.saveAs(jpg_file, ps.JPEGSaveOptions()) + print(f"Save jpg to {jpg_file}") + os.startfile(jpg_file) +``` + +### add_start_application_event.py + +Add event for Photoshop start application. + +```python +"""Add event for Photoshop start application. + +In the current example, every time we start photoshop it will +alert "Start Application Event". + +Just like you manually in Script> Script Events Manager to enable the event. + +""" + + +from __future__ import annotations +# Import built-in modules +import os + +from tempfile import mkdtemp + +# Import local modules +from photoshop import Session + + +with Session() as ps: + root = mkdtemp() + jsx_file = os.path.join(root, "event.jsx") + with open(jsx_file, "w") as f: + f.write('alert("Start Application event.")') + ps.app.notifiers.add(ps.EventID.Notify, jsx_file) + print("Add event done.") +``` + +### apply_crystallize_filter_action.py + +This script demonstrates how you can use the action manager + +```python +""" This script demonstrates how you can use the action manager + +to execute the Crystallize filter. +In order to find all the IDs, see https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin # noqa: E501 +This blog here explains what a script listener is http://blogs.adobe.com/crawlspace/2006/05/installing_and_1.html + +References: + https://github.com/lohriialo/photoshop-scripting-python/blob/master/ApplyCrystallizeFilterAction.py + +""" + + +from __future__ import annotations +# Import local modules +import examples._psd_files as psd # Import from examples. + +from photoshop import Session + + +PSD_FILE = psd.get_psd_files() + +with Session(PSD_FILE["layer_comps.psd"], "open") as ps: + active_document = ps.active_document + nLayerSets = active_document.layerSets + print(f"The total amount of current layerSet (Group) is " f"{len(nLayerSets)}.") + nArtLayers = active_document.layerSets.item(len(nLayerSets)).artLayers + + # get the last layer in LayerSets + active_document.activeLayer = active_document.layerSets.item(len(nLayerSets)).artLayers.item(len(nArtLayers)) + + def applyCrystallize(cellSize): + cellSizeID = ps.app.CharIDToTypeID("ClSz") + eventCrystallizeID = ps.app.CharIDToTypeID("Crst") + + filterDescriptor = ps.ActionDescriptor + filterDescriptor.putInteger(cellSizeID, cellSize) + + ps.app.executeAction(eventCrystallizeID, filterDescriptor) + + applyCrystallize(25) + print("Apply crystallize done.") +``` + +### apply_filters.py + +Example of applying various filters to layers in Photoshop. + +```python +"""Example of applying various filters to layers in Photoshop. + +This example demonstrates how to: +1. Apply different types of Photoshop filters +2. Configure filter parameters +3. Work with filter options +4. Handle filter application to different layer types + +Key concepts: +- Filter types and options +- Layer filtering +- Parameter configuration +- Filter effects management +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + layer = doc.activeLayer + + # Apply Gaussian Blur filter + filter_options = ps.GaussianBlurOptions() + filter_options.radius = 10.0 + layer.applyGaussianBlur(filter_options) + + # Create new layer for other filters + new_layer = doc.artLayers.add() + + # Apply Motion Blur + motion_options = ps.MotionBlurOptions() + motion_options.angle = 45 + motion_options.distance = 20 + new_layer.applyMotionBlur(motion_options) + + # Apply Smart Sharpen + sharpen_options = ps.SmartSharpenOptions() + sharpen_options.amount = 100 + sharpen_options.radius = 3.0 + sharpen_options.noiseReduction = 20 + new_layer.applySmartSharpen(sharpen_options) + + # Apply Unsharp Mask + unsharp_options = ps.UnsharpMaskOptions() + unsharp_options.amount = 50 + unsharp_options.radius = 2.0 + unsharp_options.threshold = 0 + new_layer.applyUnsharpMask(unsharp_options) +``` + +### change_color_of_background_and_foreground.py + +Example of changing background and foreground colors in Photoshop. + +```python +"""Example of changing background and foreground colors in Photoshop. + +This example demonstrates how to: +1. Set foreground and background colors +2. Work with color swatches +3. Switch between foreground and background colors +4. Reset colors to default values + +Key concepts: +- Color management +- Foreground/background colors +- Color swatches +- Default colors +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Create new colors + fg_color = ps.SolidColor() + fg_color.rgb.red = 255 + fg_color.rgb.green = 0 + fg_color.rgb.blue = 0 + + bg_color = ps.SolidColor() + bg_color.rgb.red = 0 + bg_color.rgb.green = 0 + bg_color.rgb.blue = 255 + + # Set foreground and background colors + ps.app.foregroundColor = fg_color + ps.app.backgroundColor = bg_color + + # Print current colors + print(f"Foreground RGB: {ps.app.foregroundColor.rgb.red}, " + f"{ps.app.foregroundColor.rgb.green}, " + f"{ps.app.foregroundColor.rgb.blue}") + + print(f"Background RGB: {ps.app.backgroundColor.rgb.red}, " + f"{ps.app.backgroundColor.rgb.green}, " + f"{ps.app.backgroundColor.rgb.blue}") +``` + +### color.py + +Example of working with colors in Photoshop. + +```python +"""Example of working with colors in Photoshop. + +This example demonstrates how to: +1. Create and modify solid colors +2. Work with different color models (RGB, CMYK, HSB) +3. Set foreground and background colors +4. Compare color values + +Key concepts: +- Color models +- Color manipulation +- Color space conversion +- Color comparison +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Create a new RGB color + rgb_color = ps.SolidColor() + rgb_color.rgb.red = 255 + rgb_color.rgb.green = 0 + rgb_color.rgb.blue = 0 + + # Create a new CMYK color + cmyk_color = ps.SolidColor() + cmyk_color.cmyk.cyan = 0 + cmyk_color.cmyk.magenta = 100 + cmyk_color.cmyk.yellow = 100 + cmyk_color.cmyk.black = 0 + + # Set as foreground color + ps.app.foregroundColor = rgb_color + + # Create HSB color + hsb_color = ps.SolidColor() + hsb_color.hsb.hue = 360 + hsb_color.hsb.saturation = 100 + hsb_color.hsb.brightness = 100 + + # Set as background color + ps.app.backgroundColor = hsb_color +``` + +### compare_colors.py + +Example of comparing colors in Photoshop. + +```python +"""Example of comparing colors in Photoshop. + +This example demonstrates how to: +1. Compare colors across different color models +2. Convert between color spaces +3. Check color equality +4. Work with color tolerances + +Key concepts: +- Color comparison +- Color space conversion +- Color equality testing +- Color model differences +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Create two colors for comparison + color1 = ps.SolidColor() + color1.rgb.red = 255 + color1.rgb.green = 0 + color1.rgb.blue = 0 + + color2 = ps.SolidColor() + color2.rgb.red = 255 + color2.rgb.green = 0 + color2.rgb.blue = 0 + + # Compare colors + is_same = (color1.rgb.red == color2.rgb.red and + color1.rgb.green == color2.rgb.green and + color1.rgb.blue == color2.rgb.blue) + + print(f"Colors are {'same' if is_same else 'different'}") +``` + +### convert_smartobject_to_layer.py + +Example of converting between smart objects and regular layers. + +```python +"""Example of converting between smart objects and regular layers. + +This example demonstrates how to: +1. Convert layers to smart objects +2. Convert smart objects back to regular layers +3. Manage smart object properties +4. Handle smart object conversions + +Key concepts: +- Smart Objects +- Layer conversion +- Smart Object properties +- Layer types +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Create a new layer + layer = doc.artLayers.add() + layer.name = "Test Layer" + + # Convert to smart object + layer.convertToSmartObject() + print("Layer converted to Smart Object") + + # Check if it's a smart object + if layer.kind == ps.LayerKind.SmartObjectLayer: + print("Layer is now a Smart Object") + + # Convert back to regular layer + layer.rasterize(ps.RasterizeType.EntireLayer) + print("Smart Object converted back to regular layer") +``` + +### copy_and_paste.py + +References: https://github.com/lohriialo/photoshop-scripting-python/blob/master/CopyAndPaste.py + +```python +""" +References: + https://github.com/lohriialo/photoshop-scripting-python/blob/master/CopyAndPaste.py + +""" + +# Import local modules +import photoshop.api as ps + + +app = ps.Application() + +startRulerUnits = app.preferences.rulerUnits + +app.preferences.rulerUnits = ps.Units.Inches + +doc = app.documents.add(7, 5, 72, None, ps.NewDocumentMode.NewRGB, ps.DocumentFill.White) + +# Make sure the active layer is not a text layer, which cannot be copied to the +# clipboard. +if doc.activeLayer.kind != ps.LayerKind.TextLayer: + # Select the left half of the document. Selections are always expressed + # in pixels regardless of the current ruler unit type, so we're computing + # the selection corner points based on the inch unit width and height + # of the document + x2 = (doc.width * doc.resolution) / 2 + y2 = doc.height * doc.resolution + + sel_area = ((0, 0), (x2, 0), (x2, y2), (0, y2)) + doc.selection.select(sel_area, ps.SelectionType.ReplaceSelection, 0, False) + + doc.selection.copy() + + # The new doc is created + # need to change ruler units to pixels because x2 and y2 are pixel units. + app.preferences.rulerUnits = ps.Units.Pixels + pasteDoc = app.documents.add(x2, y2, doc.resolution, "Paste Target") + pasteDoc.paste() +else: + print("You cannot copy from a text layer") + +if startRulerUnits != app.preferences.rulerUnits: + app.preferences.rulerUnits = startRulerUnits +``` + +### create_new_document.py + +Example of creating a new document in Photoshop. + +```python +"""Example of creating a new document in Photoshop. + +This example demonstrates how to: +1. Create a new document with specific dimensions +2. Set document properties like name and mode +3. Work with document units and resolution + +Key concepts: +- Document creation +- Document properties +- Color mode settings +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Create a new document with specific dimensions + doc = ps.app.documents.add( + width=1920, + height=1080, + resolution=72, + name="New Document Example" + ) +``` + +### create_thumbnail.py + +Create a thumbnail image for currently active document. + +```python +"""Create a thumbnail image for currently active document. + +You can use the thumbnail image to upload to Shotgun or Ftrack. + +""" + + +from __future__ import annotations +# Import built-in modules +import os + +from tempfile import mkdtemp + +# Import local modules +from photoshop import Session + + +def create_thumbnail(output_path=None, max_resolution=512): + """Create a thumbnail image for currently active document. + + Args: + output_path (str): The absolute output path of the thumbnail image. + The default is to output to a temporary folder. + max_resolution (int): The max resolution of the thumbnail. The default + is `512`. + + Returns: + str: The absolute output path of the thumbnail image. + + """ + output_path = output_path or os.path.join(mkdtemp(), "thumb.jpg") + + with Session(auto_close=True) as ps: + orig_name = ps.active_document.name + width_str = ps.active_document.width + height_str = ps.active_document.height + thumb_name = f"{orig_name}_thumb" + + max_resolution = width_str / max_resolution + thumb_width = int(width_str / max_resolution) + thumb_height = int(height_str / max_resolution) + + thumb_doc = ps.active_document.duplicate(thumb_name) + thumb_doc.resizeImage(thumb_width, thumb_height - 100) + thumb_doc.saveAs(output_path, ps.JPEGSaveOptions(), asCopy=True) + thumb_doc.close() + return output_path + + +if __name__ == "__main__": + thumb_file = create_thumbnail() + print(f"Save thumbnail file to {thumb_file}.") +``` + +### creating_a_layer.py + +Example of creating and manipulating layers in Photoshop. + +```python +"""Example of creating and manipulating layers in Photoshop. + +This example demonstrates how to: +1. Create different types of layers +2. Set layer properties and attributes +3. Organize layers in the document +4. Apply basic layer effects + +Key concepts: +- Layer creation +- Layer types (art layers, text layers) +- Layer properties +- Layer organization +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Create a new art layer + new_layer = doc.artLayers.add() + + # Set layer properties + new_layer.name = "New Art Layer" + new_layer.opacity = 75 + new_layer.visible = True + + # Create a text layer + text_layer = doc.artLayers.add() + text_layer.kind = ps.LayerKind.TextLayer + + # Configure text properties + text_item = text_layer.textItem + text_item.contents = "Sample Text" + text_item.size = 72 + text_item.position = [100, 100] + + # Move layers in stack + new_layer.move(text_layer, ps.ElementPlacement.PlaceAfter) +``` + +### cropping.py + +A cropping example. + +```python +"""A cropping example.""" + +# Import local modules +from photoshop import Session + + +with Session(action="new_document") as ps: + ps.active_document.crop(bounds=[100, 12, 354, 246], width=1920, height=1080) +``` + +### current_tool.py + +Example of working with Photoshop tools. + +```python +"""Example of working with Photoshop tools. + +This example demonstrates how to: +1. Get the current active tool +2. Change tools programmatically +3. Configure tool options +4. Work with tool presets + +Key concepts: +- Tool selection +- Tool properties +- Tool management +- Active tool state +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Get current tool + current = ps.app.currentTool + + # Print current tool name + print(f"Current tool: {current}") +``` + +### delete_and_fill_selection.py + +This script demonstrates how to delete and fill a selection in one operation. + +```python +"""This script demonstrates how to delete and fill a selection in one operation.""" + + +from __future__ import annotations +# Import built-in modules +import os + +# Import third-party modules +from _psd_files import get_psd_files + +# Import local modules +import photoshop.api as ps + +from photoshop.api import SolidColor + + +def delete_and_fill_selection(doc, fill_type, mode=None, opacity=None, preserve_transparency=None): + """Delete current selection and fill it with specified color. + + Args: + doc: The active document. + fill_type (SolidColor): The color to fill the selection with. + mode (ColorBlendMode, optional): The color blend mode. + opacity (int, optional): The opacity value. + preserve_transparency (bool, optional): If true, preserves transparency. + """ + # First fill the selection + doc.selection.fill(fill_type, mode, opacity, preserve_transparency) + # Then deselect + doc.selection.deselect() + +def main(): + """Create a selection and fill it with a solid color.""" + psd_file = get_psd_files()["export_layers_as_png.psd"] + + # Initialize Photoshop application + app = ps.Application() + + # Open the test file + if not os.path.exists(psd_file): + raise FileNotFoundError(f"Test file not found: {psd_file}") + app.load(psd_file) + + # Get the active document + doc = app.activeDocument + + # Create a rectangular selection + doc.selection.select(((100, 100), (400, 100), (400, 300), (100, 300))) + + # Create a solid color (red in this case) + red_color = SolidColor() + red_color.rgb.red = 255 + red_color.rgb.green = 0 + red_color.rgb.blue = 0 + + # Delete and fill the selection + delete_and_fill_selection(doc, red_color, opacity=80) + + # Save the changes + doc.save() + + print("Selection has been filled with red color.") + +if __name__ == "__main__": + main() +``` + +### do_photoshop_action.py + +Example of executing Photoshop actions. + +```python +"""Example of executing Photoshop actions. + +This example demonstrates how to: +1. Play recorded Photoshop actions +2. Work with action sets +3. Handle action execution +4. Manage action parameters + +Key concepts: +- Action playback +- Action sets +- Action execution +- Automation +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Play default Photoshop action + ps.app.doAction("action_name", "set_name") +``` + +### emboss_action.py + +emboss action + +```python +# Import local modules +from photoshop import Session + + +with Session() as ps: + app = ps.app + for index, x in enumerate(range(50)): + # Execute an existing action from action palette. + idPly = app.charIDToTypeID("Ply ") + desc8 = ps.ActionDescriptor() + idnull = app.charIDToTypeID("null") + ref3 = ps.ActionReference() + idActn = app.charIDToTypeID("Actn") + ref3.putName(idActn, "Sepia Toning (layer)") + idASet = app.charIDToTypeID("ASet") + ref3.PutName(idASet, "Default Actions") + desc8.putReference(idnull, ref3) + app.executeAction(idPly, desc8, ps.DialogModes.DisplayNoDialogs) + + # Create solid color fill layer. + idMk = app.charIDToTypeID("Mk ") + desc21 = ps.ActionDescriptor() + idNull = app.charIDToTypeID("null") + ref12 = ps.ActionReference() + idContentLayer1 = app.stringIDToTypeID("contentLayer") + ref12.putClass(idContentLayer1) + desc21.putReference(idNull, ref12) + idUsng = app.charIDToTypeID("Usng") + desc22 = ps.ActionDescriptor() + idType = app.charIDToTypeID("Type") + desc23 = ps.ActionDescriptor() + idClr = app.charIDToTypeID("Clr ") + desc24 = ps.ActionDescriptor() + idRd = app.charIDToTypeID("Rd ") + desc24.putDouble(idRd, index) + idGrn = app.charIDToTypeID("Grn ") + desc24.putDouble(idGrn, index) + idBl = app.charIDToTypeID("Bl ") + desc24.putDouble(idBl, index) + idRGBC = app.charIDToTypeID("RGBC") + desc23.putObject(idClr, idRGBC, desc24) + idSolidColorLayer = app.StringIDToTypeID("solidColorLayer") + desc22.putObject(idType, idSolidColorLayer, desc23) + idContentLayer2 = app.StringIDToTypeID("contentLayer") + desc21.putObject(idUsng, idContentLayer2, desc22) + app.executeAction(idMk, desc21, ps.DialogModes.DisplayNoDialogs) + + # Select mask. + idSlct = app.charIDToTypeID("slct") + desc38 = ps.ActionDescriptor() + idNull1 = app.charIDToTypeID("null") + ref20 = ps.ActionReference() + idChnl1 = app.charIDToTypeID("Chnl") + idChnl2 = app.charIDToTypeID("Chnl") + idMsk = app.charIDToTypeID("Msk ") + ref20.putEnumerated(idChnl1, idChnl2, idMsk) + desc38.putReference(idNull1, ref20) + idMkVs = app.charIDToTypeID("MkVs") + desc38.putBoolean(idMkVs, False) + app.executeAction(idSlct, desc38, ps.DialogModes.DisplayNoDialogs) + + app.activeDocument.activeLayer.invert() +``` + +### enable_generator.py + +Enable Generator features. + +```python +"""Enable Generator features.""" +# Import local modules +from photoshop import Session + + +with Session() as ps: + plugin_name = "generator-assets-dummy-menu" + generatorDesc = ps.ActionDescriptor + generatorDesc.putString(ps.app.stringIDToTypeID("name"), plugin_name) + ps.app.executeAction(ps.app.stringIDToTypeID("generateAssets"), generatorDesc) +``` + +### eval_javascript.py + +Example of executing JavaScript code in Photoshop. + +```python +"""Example of executing JavaScript code in Photoshop. + +This example demonstrates how to: +1. Execute JavaScript commands +2. Interact with Photoshop's scripting engine +3. Handle JavaScript results +4. Pass data between Python and JavaScript + +Key concepts: +- JavaScript execution +- Script integration +- Data exchange +- Command execution +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Execute JavaScript command + js_code = "app.documents.length" + result = ps.app.eval_javascript(js_code) + print(f"Number of open documents: {result}") +``` + +### export_artboards.py + +Example of how to export artboards from a PSD file. + +```python +"""Example of how to export artboards from a PSD file. + +This script demonstrates how to: +1. Identify artboard layers in a PSD file +2. Export each artboard as a separate image +""" + +from __future__ import annotations +# Import built-in modules +import os.path + +from pathlib import Path +from typing import List +from typing import Union + +# Import local modules +from photoshop import Session +from photoshop.api._artlayer import ArtLayer +from photoshop.api._layerSet import LayerSet +from photoshop.api.enumerations import LayerKind + + +def is_artboard(layer: Union[ArtLayer, LayerSet], ps) -> bool: + """Check if a layer is an artboard. + + Args: + layer: Photoshop layer object (ArtLayer or LayerSet) + ps: Photoshop session object + + Returns: + bool: True if the layer is an artboard, False otherwise + """ + try: + return layer.kind == LayerKind.ArtboardLayer + except Exception as e: + print(f"Error checking layer {layer.name}: {str(e)}") + # Fallback to checking layer name + return "Artboard" in layer.name + + +def get_all_layers(doc) -> List[Union[ArtLayer, LayerSet]]: + """Recursively get all layers from document, including nested layers. + + Args: + doc: Photoshop document object + + Returns: + List[Union[ArtLayer, LayerSet]]: List of all layers + """ + def _get_layers(layer_container) -> List[Union[ArtLayer, LayerSet]]: + layers = [] + + # Get art layers + for layer in layer_container.artLayers: + layers.append(layer) + + # Get layer sets and their children + for layer_set in layer_container.layerSets: + layers.append(layer_set) + layers.extend(_get_layers(layer_set)) + + return layers + + return _get_layers(doc) + + +def get_artboard_layers(doc, artboard_name: str) -> List[Union[ArtLayer, LayerSet]]: + """Get all layers that belong to an artboard. + + Args: + doc: Photoshop document object + artboard_name: Name of the artboard + + Returns: + List[Union[ArtLayer, LayerSet]]: List of layers that belong to this artboard + """ + try: + # Get all layers in the document + all_layers = [] + for layer in doc.artLayers: + all_layers.append(layer) + for layer in doc.layerSets: + all_layers.append(layer) + + # Get the artboard layer + artboard = None + for layer in all_layers: + if layer.name == artboard_name: + artboard = layer + break + + if not artboard: + return [] + + # Get all layers that belong to this artboard + artboard_layers = [] + for layer in all_layers: + if layer.name != artboard_name: + try: + # Check if layer is visible and within artboard bounds + if layer.visible and isinstance(layer, ArtLayer): + artboard_layers.append(layer) + except Exception as e: + print(f"Error checking layer {layer.name}: {str(e)}") + continue + + return artboard_layers + except Exception as e: + print(f"Error getting artboard layers: {str(e)}") + return [] + + +def export_artboards(psd_path: str, output_dir: str) -> None: + """Export all artboards in a PSD file as separate images. + + Args: + psd_path (str): Path to the PSD file + output_dir (str): Directory to save the exported images + """ + with Session() as ps: + try: + # Open the PSD file + ps.app.open(os.path.abspath(psd_path)) + doc = ps.active_document + + # Create output directory if it doesn't exist + Path(output_dir).mkdir(parents=True, exist_ok=True) + + # Get all layers including nested ones + all_layers = get_all_layers(doc) + print(f"Found {len(all_layers)} total layers:") + for layer in all_layers: + layer_type = "LayerSet" if isinstance(layer, LayerSet) else "ArtLayer" + is_ab = "Artboard" if is_artboard(layer, ps) else "Regular Layer" + print(f"Layer: {layer.name} ({layer_type} - {is_ab})") + + # Iterate through all layers + for layer in all_layers: + if is_artboard(layer, ps): + print(f"\nProcessing artboard: {layer.name}") + + # Export artboard using JavaScript + output_path = os.path.abspath(str(Path(output_dir) / f"{layer.name}.png")) + # Convert Windows path to JavaScript path format + js_path = output_path.replace("\\", "/") + + js_code = """ + function exportArtboard(filePath, artboardName) { + var doc = app.activeDocument; + var artboard = null; + + // Find the artboard + for (var i = 0; i < doc.layers.length; i++) { + if (doc.layers[i].name === '%s') { + artboard = doc.layers[i]; + break; + } + } + + if (!artboard) return; + + // Save the current state + var docState = doc.activeHistoryState; + + try { + // Hide all layers + for (var i = 0; i < doc.layers.length; i++) { + doc.layers[i].visible = false; + } + + // Show only the artboard and its contents + + +# ... truncated ... +``` + +### export_document.py + +Example of exporting a Photoshop document to different formats. + +```python +"""Example of exporting a Photoshop document to different formats. + +This example demonstrates how to: +1. Save documents in different formats (JPG, PNG) +2. Configure export quality settings +3. Handle file paths and naming +4. Use save options for different formats + +Key concepts: +- File format conversion +- Export quality control +- Save options configuration +- File path handling +""" + +# Import built-in modules +import os + +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Get the directory of current script + current_dir = os.path.dirname(__file__) + + # Save as JPG with high quality + jpg_opt = ps.JPEGSaveOptions(quality=12) + jpg_path = os.path.join(current_dir, "output.jpg") + doc.saveAs(jpg_path, jpg_opt) + + # Save as PNG with transparency + png_opt = ps.PhotoshopSaveOptions() + png_path = os.path.join(current_dir, "output.png") + doc.saveAs(png_path, png_opt) +``` + +### export_document_with_options.py + +This example demonstrates how to export a document with different formats. + +```python +"""This example demonstrates how to export a document with different formats. + +References: + https://github.com/loonghao/photoshop-python-api/issues/368 +""" + + +from __future__ import annotations +# Import built-in modules +import os + +# Import local modules +from photoshop import Session +from photoshop.api.enumerations import DitherType +from photoshop.api.enumerations import ExportType +from photoshop.api.enumerations import SaveDocumentType +from photoshop.api.save_options.jpg import JPEGSaveOptions +from photoshop.api.save_options.png import ExportOptionsSaveForWeb +from photoshop.api.save_options.png import PNGSaveOptions + + +def main(): + """Export document with different formats.""" + psd_file = os.path.join(os.path.dirname(__file__), "files", "export_layers_as_png.psd") + if not os.path.exists(psd_file): + raise FileNotFoundError( + f"File not found: {psd_file}" + ) + + # Start a new photoshop session + with Session(psd_file, "open") as ps: + doc = ps.active_document + + # Export as PNG-24 + png_path = os.path.join(os.path.dirname(__file__), "exported_png24.png") + png_options = PNGSaveOptions() + png_options.interlaced = False # Disable interlacing for better quality + png_options.compression = 0 # Set compression to 0 for maximum quality + doc.saveAs(png_path, png_options, True) # True for saving as copy + print(f"Exported PNG-24: {png_path}") + + # Export as JPEG with high quality + jpg_path = os.path.join(os.path.dirname(__file__), "exported_jpeg.jpg") + jpg_options = JPEGSaveOptions() + jpg_options.quality = 12 # Set quality to maximum (12) + jpg_options.embedColorProfile = True # Preserve color profile + jpg_options.formatOptions = 1 # Use standard baseline format + jpg_options.scans = 3 # Enable progressive scanning + jpg_options.matte = 1 # No background color (matte) + doc.saveAs(jpg_path, jpg_options, True) # True for saving as copy + print(f"Exported JPEG: {jpg_path}") + + # Export as GIF using Save for Web + gif_path = os.path.join(os.path.dirname(__file__), "exported_gif.gif") + gif_options = ExportOptionsSaveForWeb() + gif_options.format = SaveDocumentType.CompuServeGIFSave # Set format to GIF + gif_options.colors = 256 # Use maximum number of colors (256) + gif_options.dither = DitherType.NoDither # Disable dithering for sharper edges + gif_options.transparency = True # Preserve transparency in the GIF + doc.exportDocument(gif_path, ExportType.SaveForWeb, gif_options) + print(f"Exported GIF: {gif_path}") + + +if __name__ == "__main__": + main() +``` + +### export_layers_as_png.py + +Example of exporting individual layers as PNG files. + +```python +"""Example of exporting individual layers as PNG files. + +This example demonstrates how to: +1. Export each layer of a document as a separate PNG file +2. Handle layer visibility during export +3. Manage layer selection and activation +4. Configure export settings for PNG format + +Key concepts: +- Layer iteration +- Visibility management +- PNG export settings +- File naming conventions +- Layer selection +""" + +# Import built-in modules +import os + +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Store original layer visibilities + layer_visibilities = [] + for layer in doc.layers: + layer_visibilities.append(layer.visible) + layer.visible = False + + try: + # Export each layer individually + for i, layer in enumerate(doc.layers): + # Show only current layer + layer.visible = True + + # Configure PNG save options + options = ps.PNGSaveOptions() + options.interlaced = False + + # Generate unique filename for each layer + file_path = os.path.join( + os.path.dirname(__file__), + f"layer_{i}_{layer.name}.png" + ) + + # Save the file + doc.saveAs(file_path, options, True) + + # Hide the layer again + layer.visible = False + + finally: + # Restore original layer visibilities + for layer, visibility in zip(doc.layers, layer_visibilities): + layer.visible = visibility +``` + +### export_layers_use_export_options_saveforweb.py + +Export every layer as a .png file use `ExportOptionsSaveForWeb`. + +```python +"""Export every layer as a .png file use `ExportOptionsSaveForWeb`.""" + +from __future__ import annotations +# Import built-in modules +import os + +# Import local modules +import examples._psd_files as psd # Import from examples. + +from photoshop import Session + + +PSD_FILE = psd.get_psd_files() + + +def hide_all_layers(layers): + for layer in layers: + layer.visible = False + + +def main(): + psd_file = PSD_FILE["export_layers_as_png.psd"] + with Session(psd_file, action="open") as ps: + doc = ps.active_document + options = ps.ExportOptionsSaveForWeb() + layers = doc.artLayers + for layer in layers: + hide_all_layers(layers) + layer.visible = True + layer_path = os.path.join(doc.path, layer.name) + print(layer_path) + if not os.path.exists(layer_path): + os.makedirs(layer_path) + image_path = os.path.join(layer_path, f"{layer.name}.png") + doc.exportDocument(image_path, exportAs=ps.ExportType.SaveForWeb, options=options) + ps.alert("Task done!") + print(doc.activeLayer) + + +if __name__ == "__main__": + main() +``` + +### fill_selection.py + +Example of filling selections in Photoshop. + +```python +"""Example of filling selections in Photoshop. + +This example demonstrates how to: +1. Create and modify selections +2. Fill selections with colors +3. Work with selection options +4. Apply different fill methods + +Key concepts: +- Selection tools +- Fill operations +- Color fills +- Selection modification +- Fill opacity and blending +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Create a rectangular selection + doc.selection.select([ + [100, 100], + [300, 100], + [300, 200], + [100, 200] + ]) + + # Create fill color + fill_color = ps.SolidColor() + fill_color.rgb.red = 255 + fill_color.rgb.green = 0 + fill_color.rgb.blue = 0 + + # Fill the selection + doc.selection.fill(fill_color) + + # Deselect + doc.selection.deselect() + + # Create another selection and fill with opacity + doc.selection.select([ + [150, 150], + [350, 150], + [350, 250], + [150, 250] + ]) + + fill_color.rgb.blue = 255 + doc.selection.fill(fill_color, ps.ColorBlendMode.Normal, 50) + + # Clear selection + doc.selection.deselect() +``` + +### fit_on_screen.py + +Let the current document Fit on screen. + +```python +"""Let the current document Fit on screen.""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + ps.app.runMenuItem(ps.app.charIDToTypeID("FtOn")) +``` + +### get_document_by_name.py + +Example of retrieving a Photoshop document by its name. + +```python +"""Example of retrieving a Photoshop document by its name. + +This example demonstrates how to: +1. Access documents in the Photoshop application +2. Find a specific document by its name +3. Handle cases when the document doesn't exist + +Key concepts: +- Using the documents collection +- Document name comparison +- Error handling for missing documents +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Try to get document named 'test.psd' + for doc in ps.app.documents: + if doc.name == "test.psd": + print(doc.name) + break + else: + print("Document not found!") +``` + +### get_layer_by_name.py + +Example of retrieving a layer by its name in Photoshop. + +```python +"""Example of retrieving a layer by its name in Photoshop. + +This example demonstrates how to: +1. Access layers in the active document +2. Find a specific layer by its name +3. Handle layer search in the document hierarchy + +Key concepts: +- Layer navigation +- Name-based layer lookup +- Active document context +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Access active document's layers + doc = ps.app.activeDocument + for layer in doc.layers: + if layer.name == "example layer": + print(layer.name) + break +``` + +### hello_world.py + +Basic example demonstrating Photoshop automation with python-photoshop-api. + +```python +"""Basic example demonstrating Photoshop automation with python-photoshop-api. + +This example demonstrates how to: +1. Connect to Photoshop application +2. Create a new document +3. Add text content to the document +4. Save the document as PSD file + +Key concepts: +- Application connection +- Document creation +- Text layer manipulation +- File saving +""" + +# Import built-in modules +import os + +# Import local modules +from photoshop import Session + + +with Session() as ps: + # Create a new document + doc = ps.app.documents.add() + + # Create text layer with "Hello, World!" + text_color = ps.SolidColor() + text_color.rgb.red = 255 + text_color.rgb.green = 0 + text_color.rgb.blue = 0 + + new_text_layer = doc.artLayers.add() + new_text_layer.kind = ps.LayerKind.TextLayer + new_text_layer.textItem.contents = "Hello, World!" + new_text_layer.textItem.position = [160, 167] + new_text_layer.textItem.size = 40 + new_text_layer.textItem.color = text_color + + # Save the document + jpg_file = os.path.join(os.path.dirname(__file__), "hello_world.jpg") + ps.JPEGSaveOptions(quality=12) + doc.saveAs(jpg_file) +``` + +### import_image_as_layer.py + +Import a image as a artLayer. + +```python +"""Import a image as a artLayer.""" + +# Import local modules +from photoshop import Session + + +with Session(action="new_document") as ps: + desc = ps.ActionDescriptor + desc.putPath(ps.app.charIDToTypeID("null"), "your/image/path") + event_id = ps.app.charIDToTypeID("Plc ") # `Plc` need one space in here. + ps.app.executeAction(ps.app.charIDToTypeID("Plc "), desc) +``` + +### link_layer.py + +Example of linking layers in Photoshop. + +```python +"""Example of linking layers in Photoshop. + +This example demonstrates how to: +1. Link multiple layers together +2. Manage linked layers +3. Check layer link status +4. Modify linked layer properties + +Key concepts: +- Layer linking +- Group operations +- Layer management +- Link status +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Create test layers + layer1 = doc.artLayers.add() + layer1.name = "Layer 1" + + layer2 = doc.artLayers.add() + layer2.name = "Layer 2" + + layer3 = doc.artLayers.add() + layer3.name = "Layer 3" + + # Link layers + layer1.link(layer2) + layer2.link(layer3) + + # Check link status + print(f"Layer 1 linked: {layer1.linked}") + print(f"Layer 2 linked: {layer2.linked}") + print(f"Layer 3 linked: {layer3.linked}") + + # Move linked layers together + layer1.translate(100, 100) +``` + +### list_documents.py + +List current photoshop all documents. + +```python +"""List current photoshop all documents.""" + +# Import local modules +import photoshop.api as ps + + +app = ps.Application() + +doc = app.documents[0] +print(doc.name) + +for doc in app.documents: + print(doc.name) +``` + +### load_selection.py + +Example of loading and working with selections in Photoshop. + +```python +"""Example of loading and working with selections in Photoshop. + +This example demonstrates how to: +1. Create and save selections +2. Load saved selections +3. Modify selection channels +4. Combine multiple selections + +Key concepts: +- Selection channels +- Channel operations +- Selection saving/loading +- Selection modification +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Create initial selection + doc.selection.select([ + [100, 100], + [300, 100], + [300, 300], + [100, 300] + ]) + + # Save selection to channel + doc.channels.add() + doc.selection.store(doc.channels[-1]) + + # Deselect everything + doc.selection.deselect() + + # Create another selection + doc.selection.select([ + [200, 200], + [400, 200], + [400, 400], + [200, 400] + ]) + + # Save to another channel + doc.channels.add() + doc.selection.store(doc.channels[-1]) + + # Load first selection + doc.selection.load(doc.channels[-2]) + + # Combine with second selection + doc.selection.combine(doc.channels[-1], ps.SelectionType.ExtendSelection) + + # Clean up - delete added channels + doc.channels[-1].delete() + doc.channels[-1].delete() +``` + +### move_to_end.py + +Example of moving layers to different positions in the layer stack. + +```python +"""Example of moving layers to different positions in the layer stack. + +This example demonstrates how to: +1. Move layers within the layer stack +2. Change layer order +3. Handle layer positioning +4. Work with layer groups + +Key concepts: +- Layer ordering +- Layer movement +- Stack manipulation +- Layer hierarchy +""" + +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # Create some test layers + layer1 = doc.artLayers.add() + layer1.name = "Layer 1" + + layer2 = doc.artLayers.add() + layer2.name = "Layer 2" + + layer3 = doc.artLayers.add() + layer3.name = "Layer 3" + + # Move layer1 to the end (bottom) of the stack + layer1.move(doc.layers[-1], ps.ElementPlacement.PlaceAfter) + + # Move layer3 to the beginning (top) of the stack + layer3.move(doc.layers[0], ps.ElementPlacement.PlaceBefore) + + # Move layer2 between layer1 and layer3 + layer2.move(layer1, ps.ElementPlacement.PlaceBefore) +``` + +### new_document.py + +new document + +```python +# Create a new Photoshop document with diminsions 4 inches by 4 inches. +# Import local modules +import photoshop.api as ps + + +# Start up Photoshop application +app = ps.Application() + +start_ruler_units = app.preferences.rulerUnits + +app.preferences.rulerUnits = ps.Units.Pixels + +# Create the document +docRef = app.documents.add(1920, 1080, 72.0, "My New Document") + +# Make sure to set the ruler units prior to creating the document. +app.preferences.rulerUnits = start_ruler_units +``` + +### open_psd.py + +open psd + +```python +from __future__ import annotations + +# Import local modules +import photoshop.api as ps + +from photoshop import Session + + +# style 1 +app = ps.Application() +app.load("your/psd/or/psb/file_path.psd") + +# style 2 +with Session("your/psd/or/psb/file_path.psd", action="open") as ps: + print(ps.active_document.name) +``` + +### operate_channels.py + +Example of working with channels in Photoshop. + +```python +"""Example of working with channels in Photoshop. + +This example demonstrates how to: +1. Access and manipulate color channels +2. Create and modify alpha channels +3. Work with channel visibility +4. Handle channel operations + +Key concepts: +- Channel management +- Alpha channels +- Channel visibility +- Color separation +""" + + +from __future__ import annotations +# Import local modules +from photoshop import Session + + +with Session() as ps: + doc = ps.active_document + + # List all channels + for channel in doc.channels: + print(f"Channel: {channel.name}") + + # Create a new alpha channel + new_channel = doc.channels.add() + new_channel.name = "Custom Alpha" + + # Duplicate a channel + if len(doc.channels) > 0: + duplicate = doc.channels[0].duplicate() + duplicate.name = "Channel Copy" + + # Toggle channel visibility + for channel in doc.channels: + channel.visible = True +``` + +(19 further examples are in `examples/`.) + +--- + +## Module index + +Public modules in the `photoshop` package: + +- `photoshop.__version__` +- `photoshop.api` +- `photoshop.api._artlayer` +- `photoshop.api._artlayers` +- `photoshop.api._channel` +- `photoshop.api._channels` +- `photoshop.api._clsid` +- `photoshop.api._core` +- `photoshop.api._document` +- `photoshop.api._documentinfo` +- `photoshop.api._documents` +- `photoshop.api._layer` +- `photoshop.api._layerComp` +- `photoshop.api._layerComps` +- `photoshop.api._layerSet` +- `photoshop.api._layerSets` +- `photoshop.api._layers` +- `photoshop.api._measurement_log` +- `photoshop.api._notifier` +- `photoshop.api._notifiers` +- `photoshop.api._preferences` +- `photoshop.api._selection` +- `photoshop.api._text_fonts` +- `photoshop.api.action_descriptor` +- `photoshop.api.action_list` +- `photoshop.api.action_reference` +- `photoshop.api.application` +- `photoshop.api.base_action` +- `photoshop.api.batch_options` +- `photoshop.api.collections` +- `photoshop.api.colors` +- `photoshop.api.colors.cmyk` +- `photoshop.api.colors.gray` +- `photoshop.api.colors.hsb` +- `photoshop.api.colors.lab` +- `photoshop.api.colors.rgb` +- `photoshop.api.constants` +- `photoshop.api.enumerations` +- `photoshop.api.errors` +- `photoshop.api.event_id` +- `photoshop.api.open_options` +- `photoshop.api.open_options.eps` +- `photoshop.api.path_item` +- `photoshop.api.path_items` +- `photoshop.api.path_point` +- `photoshop.api.path_point_info` +- `photoshop.api.protocols` +- `photoshop.api.save_options` +- `photoshop.api.save_options.bmp` +- `photoshop.api.save_options.eps` +- `photoshop.api.save_options.gif` +- `photoshop.api.save_options.jpg` +- `photoshop.api.save_options.pdf` +- `photoshop.api.save_options.png` +- `photoshop.api.save_options.psd` +- `photoshop.api.save_options.tag` +- `photoshop.api.save_options.tif` +- `photoshop.api.solid_color` +- `photoshop.api.sub_path_info` +- `photoshop.api.sub_path_item` +- `photoshop.api.text_font` +- `photoshop.api.text_item` +- `photoshop.session` diff --git a/llms.txt b/llms.txt new file mode 100644 index 00000000..3e653f39 --- /dev/null +++ b/llms.txt @@ -0,0 +1,60 @@ +# photoshop-python-api + +> A Python API for controlling Adobe Photoshop on Windows through COM +> automation. It wraps Photoshop's COM interface so scripts can open +> documents, drive layers, export images and run Photoshop actions from +> plain Python. + +Version: 0.25.0 +Package: https://pypi.org/project/photoshop-python-api/ +Source: https://github.com/loonghao/photoshop-python-api +Full documentation: https://photoshop-python-api.readthedocs.io/en/master/ + +## Getting started + +Install with `pip install photoshop-python-api`. It requires Windows and +a locally installed Adobe Photoshop. `photoshop.Session` is the entry +point: it opens Photoshop if it is not running, gives you the active +document, and exposes the API's classes and constants as attributes. + +```python +from photoshop import Session + +with Session(action='new_document') as ps: + doc = ps.active_document + text_color = ps.SolidColor() + text_color.rgb.green = 255 + new_text_layer = doc.artLayers.add() + new_text_layer.kind = ps.LayerKind.TextLayer + new_text_layer.textItem.contents = 'Hello, World!' + new_text_layer.textItem.position = [160, 167] + new_text_layer.textItem.size = 40 + new_text_layer.textItem.color = text_color + options = ps.JPEGSaveOptions(quality=5) + jpg = 'd:/hello_world.jpg' + doc.saveAs(jpg, options, asCopy=True) +``` + +## Table of contents + +- [Getting started](https://github.com/loonghao/photoshop-python-api/blob/main/README.md) — installation, requirements and supported Photoshop versions +- [API reference](https://photoshop-python-api.readthedocs.io/en/master/) — generated reference for every wrapper class +- [Examples](https://github.com/loonghao/photoshop-python-api/tree/main/examples) — 59 runnable scripts covering common tasks +- [Documentation source](https://github.com/loonghao/photoshop-python-api/tree/main/docs) — the MkDocs site sources + +## Conventions + +- All modules live under the `photoshop` package; `photoshop.api` exposes + the COM wrapper classes and `photoshop.api.enumerations` the constants. +- The quickest route to a working script is `photoshop.Session`, which + exposes the API's classes and constants as attributes on the session + object so `import photoshop.api as ps` is not needed for every name. +- Enumeration members use Photoshop's own names, so `ps.LayerKind.TextLayer` + maps to the constant Photoshop calls `LayerKind.TextLayer`. +- Every example under `examples/` is runnable as a standalone script when + Photoshop is installed. + +## Optional + +- [Changelog](https://github.com/loonghao/photoshop-python-api/blob/main/CHANGELOG.md) — release history. +- [Issue tracker](https://github.com/loonghao/photoshop-python-api/issues) — known problems and questions. diff --git a/pyproject.toml b/pyproject.toml index 118335d8..2679a128 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,9 +90,42 @@ extend-exclude = [ # Behaviour-preserving port of .flake8. The old file also configured # flake8-docstrings (google) and flake8-quotes, but neither plugin was installed # in CI, so only pycodestyle/pyflakes rules ever fired. Quote rules are enabled -# here because the codebase already satisfies them; the docstring rules are not, -# see the migration PR for the measured violation count. -select = ["E", "W", "F", "Q", "I", "UP"] +# here because the codebase already satisfies them. +# +# The docstring rules (D) are enabled but baselined per directory below: every +# finding that exists today is recorded in `per-file-ignores`, so CI stays green +# on the current tree while any NEW docstring debt is caught immediately. The +# baseline is meant to shrink — pick a tier, fix it, delete its entry. +select = ["E", "W", "F", "Q", "I", "UP", "D"] + +# Selecting the whole D family makes ruff drop the mutually exclusive half of two +# pairs on its own: D203 loses to D211, and D213 loses to D212. Both are reported +# as warnings at startup, which is expected and not something to "fix". +[tool.ruff.lint.pydocstyle] +convention = "google" + +# ── Docstring baseline ────────────────────────────────────────────────────── +# 864 findings existed when D was switched on. Each entry is a directory tier +# plus the rules that tier currently violates; the number is the finding count +# at baseline time. Deleting a rule from an entry makes that tier's existing +# debt fail CI until it is fixed, which is the intended ratchet. +[tool.ruff.lint.per-file-ignores] +# Enum constant tables: one IntEnum class per Photoshop constant, 129 findings. +"photoshop/api/enumerations.py" = ["D101"] +# Save-option wrappers, 112 findings. +"photoshop/api/save_options/**" = ["D100", "D102", "D104", "D107", "D205", "D209", "D400", "D401", "D414", "D415", "D417"] +# Open-option wrappers, 9 findings. +"photoshop/api/open_options/**" = ["D100", "D102", "D104", "D107"] +# Color model wrappers, 19 findings. +"photoshop/api/colors/**" = ["D100", "D102", "D104", "D105", "D107", "D401"] +# Manual tests driving a real Photoshop instance, 118 findings. +"test/manual_test/**" = ["D100", "D101", "D102", "D401", "D419"] +# Unit tests, 45 findings. +"test/**" = ["D100", "D101", "D102", "D103", "D104", "D105", "D107", "D202", "D401", "D403"] +# The COM wrapper API, 443 findings. +"photoshop/api/**" = ["D100", "D101", "D102", "D105", "D107", "D205", "D209", "D212", "D214", "D301", "D400", "D401", "D403", "D404", "D405", "D413", "D414", "D415", "D417"] +# Package root, 8 findings. +"photoshop/**" = ["D100", "D102", "D104", "D105", "D205", "D401", "D403"] [tool.ruff.lint.flake8-quotes] inline-quotes = "double" diff --git a/scripts/generate_llms.py b/scripts/generate_llms.py new file mode 100644 index 00000000..bef90566 --- /dev/null +++ b/scripts/generate_llms.py @@ -0,0 +1,417 @@ +"""Generate llms.txt and llms-full.txt for this repository. + +``llms.txt`` is a short, curated index that points a language model at the +documents worth reading; ``llms-full.txt`` concatenates the same content +inline so a model can consume it in one request without fetching anything. + +Both files are generated, never hand-edited. The ``llms-txt`` job in +``.github/workflows/llms-txt.yml`` regenerates them and opens a pull request +whenever the result differs from what is committed. + +Run it locally with:: + + python scripts/generate_llms.py + +Pass ``--check`` to exit non-zero when the committed files are stale, which +is how the CI job decides whether a pull request is needed. +""" + +# Import future modules +from __future__ import annotations + +# Import built-in modules +import argparse +import re +import subprocess +import sys + +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +REPO_ROOT = Path(__file__).resolve().parent.parent +OUTPUT_DIR = REPO_ROOT + +PACKAGE_NAME = "photoshop-python-api" +PROJECT_TITLE = "photoshop-python-api" +PROJECT_URL = "https://github.com/loonghao/photoshop-python-api" +DOCS_URL = "https://photoshop-python-api.readthedocs.io/en/master/" +PYPI_URL = "https://pypi.org/project/photoshop-python-api/" + +README = REPO_ROOT / "README.md" +EXAMPLES_DIR = REPO_ROOT / "examples" +PACKAGE_DIR = REPO_ROOT / "photoshop" +DOCS_DIR = REPO_ROOT / "docs" + +# Sections of the README that are navigation furniture rather than content. +# Everything before the first real heading is the badge block. +BADGE_BLOCK = re.compile(r"\A.*?\s*

\s*", re.DOTALL) + +# Trailing sections of the README that are not useful to a model solving a task. +# Matched on the first alphanumeric word of the heading so emoji suffixes such as +# "Contributors ✨" still match. +README_DROP_HEADINGS = { + "contributors", + "contributing", + "credits", + "license", + "acknowledgements", + "acknowledgments", +} + +MAX_EXAMPLES_IN_FULL = 40 +MAX_EXAMPLE_BYTES = 6000 + + +@dataclass(frozen=True) +class Link: + """One entry in the llms.txt index.""" + + title: str + url: str + description: str + + +def read(path: Path) -> str: + """Return the text of a file, or an empty string when it is absent.""" + try: + return path.read_text(encoding="utf-8") + except OSError: + return "" + + +def heading_level(line: str) -> int | None: + """Return the Markdown heading level of a line, or None if it is not one.""" + match = re.match(r"^(#{1,6})\s+\S", line) + return len(match.group(1)) if match else None + + +def strip_badges(text: str) -> str: + """Remove the HTML badge block that opens the README.""" + return BADGE_BLOCK.sub("", text, count=1).lstrip() + + +def drop_trailing_sections(text: str, dropped: set[str]) -> str: + """Return the text with the named top-level sections removed. + + A section runs from its ``##`` heading to the next heading of the same or + higher level. Only level-2 headings are matched so nested content stays. + """ + lines = text.splitlines() + kept: list[str] = [] + skipping = False + for line in lines: + level = heading_level(line) + if level is not None and level <= 2: + title = line.lstrip("#").strip().lower() + # Headings carry emoji ("Contributors ✨", "🛠️ Development Guide"), + # so match on the leading word rather than the whole string. + first_word = re.search(r"[a-z]+", title) + skipping = bool(first_word) and first_word.group(0) in dropped + if not skipping: + kept.append(line) + return "\n".join(kept) + + +def compact_blank_runs(text: str) -> str: + """Collapse runs of blank lines and drop trailing whitespace.""" + text = re.sub(r"[ \t]+$", "", text, flags=re.MULTILINE) + text = re.sub(r"\n{3,}", "\n\n", text) + return text.strip() + "\n" + + +def clean_readme() -> str: + """Return the README body without badges and without contributor boilerplate.""" + text = strip_badges(read(README)) + text = drop_trailing_sections(text, README_DROP_HEADINGS) + return compact_blank_runs(text) + + +def first_paragraph(text: str) -> str: + """Return the first prose paragraph of a Markdown document.""" + for block in re.split(r"\n\s*\n", text): + candidate = block.strip() + if not candidate or candidate.startswith(("#", "```", "|", "<", "---")): + continue + return " ".join(candidate.split()) + return "" + + +def example_files() -> list[Path]: + """Return the example scripts, sorted by name.""" + if not EXAMPLES_DIR.is_dir(): + return [] + return sorted(p for p in EXAMPLES_DIR.glob("*.py") if p.is_file()) + + +def example_description(path: Path) -> str: + """Return a one-line description of an example script from its docstring.""" + text = read(path) + match = re.search(r'"""(.*?)"""', text, re.DOTALL) + if match: + summary = first_paragraph(match.group(1)) + if summary: + return summary + # Fall back to the module name: the file names are already descriptive. + return path.stem.replace("_", " ") + + +def public_modules() -> list[str]: + """Return the dotted module names of the installed package, sorted.""" + if not PACKAGE_DIR.is_dir(): + return [] + modules: list[str] = [] + for path in sorted(PACKAGE_DIR.rglob("*.py")): + relative = path.relative_to(PACKAGE_DIR) + parts = list(relative.parts) + if parts[-1] == "__init__.py": + parts = parts[:-1] + else: + parts[-1] = parts[-1][: -len(".py")] + if not parts: + continue + modules.append("photoshop." + ".".join(parts) if parts != ["photoshop"] else "photoshop") + return sorted(set(modules)) + + +def version() -> str: + """Return the current package version from git, falling back to pyproject.""" + try: + result = subprocess.run( + ["git", "describe", "--tags", "--abbrev=0"], + cwd=REPO_ROOT, + capture_output=True, + text=True, + check=False, + ) + if result.returncode == 0 and result.stdout.strip(): + return result.stdout.strip().lstrip("v") + except OSError: + pass + pyproject = read(REPO_ROOT / "pyproject.toml") + match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject, re.MULTILINE) + return match.group(1) if match else "unknown" + + +def render_index(links: Iterable[Link]) -> str: + """Render the llms.txt index body.""" + lines = [ + f"# {PROJECT_TITLE}", + "", + "> A Python API for controlling Adobe Photoshop on Windows through COM", + "> automation. It wraps Photoshop's COM interface so scripts can open", + "> documents, drive layers, export images and run Photoshop actions from", + "> plain Python.", + "", + f"Version: {version()}", + f"Package: {PYPI_URL}", + f"Source: {PROJECT_URL}", + f"Full documentation: {DOCS_URL}", + "", + "## Getting started", + "", + "Install with `pip install photoshop-python-api`. It requires Windows and", + "a locally installed Adobe Photoshop. `photoshop.Session` is the entry", + "point: it opens Photoshop if it is not running, gives you the active", + "document, and exposes the API's classes and constants as attributes.", + "", + "```python", + "from photoshop import Session", + "", + "with Session(action='new_document') as ps:", + " doc = ps.active_document", + " text_color = ps.SolidColor()", + " text_color.rgb.green = 255", + " new_text_layer = doc.artLayers.add()", + " new_text_layer.kind = ps.LayerKind.TextLayer", + " new_text_layer.textItem.contents = 'Hello, World!'", + " new_text_layer.textItem.position = [160, 167]", + " new_text_layer.textItem.size = 40", + " new_text_layer.textItem.color = text_color", + " options = ps.JPEGSaveOptions(quality=5)", + " jpg = 'd:/hello_world.jpg'", + " doc.saveAs(jpg, options, asCopy=True)", + "```", + "", + "## Table of contents", + "", + ] + + for link in links: + summary = f" — {link.description}" if link.description else "" + lines.append(f"- [{link.title}]({link.url}){summary}") + + lines += [ + "", + "## Conventions", + "", + "- All modules live under the `photoshop` package; `photoshop.api` exposes", + " the COM wrapper classes and `photoshop.api.enumerations` the constants.", + "- The quickest route to a working script is `photoshop.Session`, which", + " exposes the API's classes and constants as attributes on the session", + " object so `import photoshop.api as ps` is not needed for every name.", + "- Enumeration members use Photoshop's own names, so `ps.LayerKind.TextLayer`", + " maps to the constant Photoshop calls `LayerKind.TextLayer`.", + "- Every example under `examples/` is runnable as a standalone script when", + " Photoshop is installed.", + "", + "## Optional", + "", + f"- [Changelog]({PROJECT_URL}/blob/main/CHANGELOG.md) — release history.", + f"- [Issue tracker]({PROJECT_URL}/issues) — known problems and questions.", + "", + ] + return "\n".join(lines) + + +def render_full(links: Iterable[Link]) -> str: + """Render the llms-full.txt body: every source document concatenated.""" + parts: list[str] = [ + f"# {PROJECT_TITLE} — full reference", + "", + f"Version: {version()}", + f"Source: {PROJECT_URL}", + f"Documentation: {DOCS_URL}", + "", + "This file concatenates the repository's documentation and example code so", + "it can be consumed in a single request. It is generated by", + "`scripts/generate_llms.py`; edit the sources, not this file.", + "", + "---", + "", + "## README", + "", + clean_readme(), + "", + "---", + "", + ] + + if links: + parts += ["---", "", "## Contents", ""] + for link in links: + summary = f" — {link.description}" if link.description else "" + parts.append(f"- [{link.title}]({link.url}){summary}") + parts.append("") + + examples = example_files() + if examples: + parts += ["---", "", "## Examples", ""] + parts.append( + "Each example is a standalone script. Constants come from" + " `photoshop.api.enumerations` and classes from `photoshop.api`." + ) + parts.append("") + for path in examples[:MAX_EXAMPLES_IN_FULL]: + body = read(path) + if len(body.encode("utf-8")) > MAX_EXAMPLE_BYTES: + body = body.encode("utf-8")[:MAX_EXAMPLE_BYTES].decode("utf-8", "ignore") + body += "\n\n# ... truncated ...\n" + parts += [ + f"### {path.name}", + "", + example_description(path), + "", + "```python", + body.strip(), + "```", + "", + ] + if len(examples) > MAX_EXAMPLES_IN_FULL: + remaining = len(examples) - MAX_EXAMPLES_IN_FULL + parts += [f"({remaining} further examples are in `examples/`.)", ""] + + modules = public_modules() + if modules: + parts += ["---", "", "## Module index", ""] + parts.append("Public modules in the `photoshop` package:") + parts.append("") + for name in modules: + parts.append(f"- `{name}`") + parts.append("") + + return "\n".join(parts) + + +def build_links() -> list[Link]: + """Return the curated index entries pointing at this repository's content.""" + links = [ + Link( + "Getting started", + f"{PROJECT_URL}/blob/main/README.md", + "installation, requirements and supported Photoshop versions", + ), + Link( + "API reference", + DOCS_URL, + "generated reference for every wrapper class", + ), + Link( + "Examples", + f"{PROJECT_URL}/tree/main/examples", + f"{len(example_files())} runnable scripts covering common tasks", + ), + ] + + docs_index = DOCS_DIR / "index.md" + if docs_index.is_file(): + links.append(Link("Documentation source", f"{PROJECT_URL}/tree/main/docs", "the MkDocs site sources")) + + return links + + +def write_if_changed(path: Path, content: str) -> bool: + """Write `content` to `path` when it differs; return True when it changed. + + Newlines are written as LF explicitly. Without it the output would follow + the platform default, so a maintainer on Windows and the CI job on Linux + would produce different bytes for the same content and undo each other. + Git normalises the result on commit either way. + """ + if path.is_file() and read(path) == content: + return False + path.write_text(content, encoding="utf-8", newline="\n") + return True + + +def main() -> int: + """Generate both files, or verify them under ``--check``.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--check", + action="store_true", + help="exit non-zero when the committed files are out of date", + ) + args = parser.parse_args() + + links = build_links() + index_text = render_index(links) + full_text = render_full(links) + + if args.check: + stale = [ + name + for name, text in (("llms.txt", index_text), ("llms-full.txt", full_text)) + if read(OUTPUT_DIR / name) != text + ] + if stale: + joined = ", ".join(stale) + print(f"::error::{joined} are out of date; run scripts/generate_llms.py") + return 1 + print("llms.txt and llms-full.txt are up to date") + return 0 + + changed = [ + name + for name, text in (("llms.txt", index_text), ("llms-full.txt", full_text)) + if write_if_changed(OUTPUT_DIR / name, text) + ] + if changed: + print("Updated: " + ", ".join(changed)) + else: + print("No changes: llms.txt and llms-full.txt are current") + return 0 + + +if __name__ == "__main__": + sys.exit(main())