From 1a048c6958d467a7afb976972ff4bd8e2efa3b31 Mon Sep 17 00:00:00 2001 From: Andreas Stefl Date: Sat, 14 Nov 2026 15:13:58 +0100 Subject: [PATCH] Write the screenshot samples with the sampledoc package The samples the store screenshots open were generated by a 1,500 line script that the Android app carried a newer copy of. Both now take them from sampledoc (https://pypi.org/project/sampledoc/), pinned at 0.1.0 in scripts/requirements.txt next to storeframe. make-screenshot-documents.py stays as the entry point and writes the languages store_screenshots.LOCALES photographs. It refuses to run against a different sampledoc version than the pinned one. The samples are the same, byte for byte, as the old script wrote. screenshot-names.json now nests the languages under "languages" and carries the locale table, as on Android; ScreenshotMode reads the new layout. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FW6WZb2gUX4HQfKXWeZ3UQ --- .github/workflows/release.yml | 6 +- OpenDocumentReader/ScreenshotMode.swift | 7 +- fastlane/screenshots/README.md | 4 +- scripts/make-screenshot-documents.py | 1572 +---------------------- scripts/requirements.txt | 6 +- 5 files changed, 60 insertions(+), 1535 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0b0cd87..4e37f8a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -208,8 +208,8 @@ jobs: with: xcode-version: ${{ env.xcode_version }} - # storeframe frames the captures; it is the one thing the scripts here - # want that is not in the standard library + # storeframe frames the captures and sampledoc writes the samples, the two + # things the scripts here want that are not in the standard library - uses: actions/setup-python@v7 with: python-version: "3.13" @@ -220,7 +220,7 @@ jobs: uses: actions/cache@v6 with: path: build/screenshots - key: screenshots-${{ matrix.device }}-${{ runner.os }}-${{ env.xcode_version }}-${{ hashFiles('OpenDocumentReader.xcodeproj/project.pbxproj', 'OpenDocumentReader.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved', 'OpenDocumentReader/**', 'OpenDocumentReaderUITests/**', 'Ads/**', 'NoAds/**', 'configs/**', 'scripts/make-screenshot-documents.py') }} + key: screenshots-${{ matrix.device }}-${{ runner.os }}-${{ env.xcode_version }}-${{ hashFiles('OpenDocumentReader.xcodeproj/project.pbxproj', 'OpenDocumentReader.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved', 'OpenDocumentReader/**', 'OpenDocumentReaderUITests/**', 'Ads/**', 'NoAds/**', 'configs/**', 'scripts/make-screenshot-documents.py', 'scripts/requirements.txt') }} # half a set, so the lane does not check it - the job below does, once # both halves are in diff --git a/OpenDocumentReader/ScreenshotMode.swift b/OpenDocumentReader/ScreenshotMode.swift index 4c48330..46b3d32 100644 --- a/OpenDocumentReader/ScreenshotMode.swift +++ b/OpenDocumentReader/ScreenshotMode.swift @@ -140,11 +140,16 @@ enum ScreenshotMode { let search: String } + /// The file's top level; it also carries the store locale table, which the app does not need. + private struct Names: Decodable { + let languages: [String: Details] + } + private static func details() -> Details? { guard let url = Bundle.main.url(forResource: "screenshot-names", withExtension: "json"), let data = try? Data(contentsOf: url), - let all = try? JSONDecoder().decode([String: Details].self, from: data) + let all = try? JSONDecoder().decode(Names.self, from: data).languages else { assertionFailure("no screenshot-names.json bundled - run scripts/make-screenshot-documents.py") diff --git a/fastlane/screenshots/README.md b/fastlane/screenshots/README.md index d44bca7..28f74bf 100644 --- a/fastlane/screenshots/README.md +++ b/fastlane/screenshots/README.md @@ -6,6 +6,7 @@ capture run writes the raw pictures to this directory and the framed set to are taken during the release run, from the build that goes out. ```sh +python3 -m pip install -r scripts/requirements.txt # storeframe and sampledoc bundle exec fastlane ios screenshots # capture, then frame python3 -m storeframe frame fastlane/frames/frames.json --platform ios \ --captured fastlane/screenshots --out fastlane/framed # frame again, without a capture @@ -14,7 +15,8 @@ python3 -m storeframe frame fastlane/frames/frames.json --platform ios \ The lane does these steps: 1. `scripts/make-screenshot-documents.py` writes the localized sample - documents. They are build output and go into Debug builds only. + documents with [sampledoc](https://github.com/opendocument-app/sampledoc). + They are build output and go into Debug builds only. 2. `fastlane snapshot` builds the `ODR Screenshots` scheme once and launches the app once per screen and locale, with `-ODRScreenshot `. See `OpenDocumentReader/ScreenshotMode.swift`. diff --git a/scripts/make-screenshot-documents.py b/scripts/make-screenshot-documents.py index 988e935..fcaec13 100755 --- a/scripts/make-screenshot-documents.py +++ b/scripts/make-screenshot-documents.py @@ -1,1559 +1,75 @@ #!/usr/bin/env python3 """Generate reproducible localized samples for Debug screenshot builds. -Usage: python3 scripts/make-screenshot-documents.py [--language en]""" +The documents come from `sampledoc` (https://github.com/opendocument-app/sampledoc), +shared with the Android app and pinned in scripts/requirements.txt. This script +picks the languages from store_screenshots.LOCALES and writes them, with +screenshot-names.json, to OpenDocumentReader/Samples. + +Usage: + python3 -m pip install -r scripts/requirements.txt + python3 scripts/make-screenshot-documents.py [--language en] +""" import argparse import json import re -import unicodedata -import zipfile from pathlib import Path -from xml.sax.saxutils import escape -# 1980-01-01, what zip stores when it is given nothing: a rerun with the same -# words has to produce the same bytes, or every run is a commit -EPOCH = (1980, 1, 1, 0, 0, 0) +import store_screenshots as store SAMPLES = Path(__file__).resolve().parent.parent / "OpenDocumentReader" / "Samples" +REQUIREMENTS = Path(__file__).resolve().with_name("requirements.txt") -NAMESPACES = " ".join( - [ - 'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"', - 'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"', - 'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"', - 'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"', - 'xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"', - 'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"', - 'xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"', - ] -) - -MANIFEST = """ - - - - - -""" - -# A4 portrait for documents; 16:9 for slides. -PAGE_LAYOUTS = { - "document": '', - "slide": '', -} - -# One accent, used for the report's headings and the slide titles, so the three -# documents read as one set. Blue, because the app's own tint is. -ACCENT = "#1c6fd6" -RULE = "#d4d9e0" - -# Place the cost table under the second report section. -COSTS_SECTION = 1 -REPORT_ROWS = 26 - - -def styles(kind: str) -> str: - return f""" - - - - - {PAGE_LAYOUTS[kind]} - - - - - - -""" - - -def content(body: str, automatic: str = "") -> str: - return f""" - - -{automatic} - - -{body} - - -""" - - -def paragraph_style(name: str, *, size: str, weight: str = "normal", colour: str = "#1a1a1a", space: str = "0.4cm") -> str: - return f""" - - - """ - - -def report(words: dict) -> str: - """Build a report with headings and a cost table long enough to fill the screenshot.""" - automatic = "\n".join( - [ - paragraph_style("Title", size="26pt", weight="bold", space="0.8cm"), - paragraph_style("Heading", size="16pt", weight="bold", colour=ACCENT, space="0.3cm"), - paragraph_style("Body", size="12pt", space="0.5cm"), - CELL_STYLES, - """ - - """, - """ - - """, - ] - ) - - head, body, foot = table(words, columns=3, rows=REPORT_ROWS) - marks = "\n".join( - [' '] - + [' '] * (len(head) - 1) - ) - figures = ( - f' \n{marks}\n' - + "\n".join([odf_row(head, "ceHead")] + [odf_row(line) for line in body] + [odf_row(foot, "ceTotal")]) - + "\n " - ) - - lines = [ - f' {escape(words["title"])}', - f' {escape(words["lead"])}', - ] - for index, (heading, paragraphs) in enumerate(words["sections"]): - lines.append( - f' {escape(heading)}' - ) - lines += [f' {escape(text)}' for text in paragraphs] - - # under the costs section, which is the one it is the figures for. Its own - # heading would be a word to translate nine times for nothing - if index == COSTS_SECTION: - lines.append(figures) - lines.append(' ') - - lines.append(f' {escape(words["closing"])}') - - return content(" \n" + "\n".join(lines) + "\n ", automatic) - - -def table(words: dict, columns: int = 4, rows: int = 0, scale: int = 1) -> tuple: - """Return header, data and totals rows for the requested periods and row count.""" - periods = words["periods"][:columns] - columns = len(periods) - taken = FIGURES[:rows] if rows else FIGURES - names = words["rows"][: len(taken)] - - head = [words["item"]] + periods + [words["total"]] - body = [ - [name] + [value * scale for value in figures[:columns]] + [sum(figures[:columns]) * scale] - for name, figures in zip(names, taken) - ] - foot = ( - [words["total"]] - + [sum(line[column + 1] for line in body) for column in range(len(periods))] - + [sum(line[-1] for line in body)] - ) - - return head, body, foot - - -def odf_row(cells: list, style: str | None = None) -> str: - """Build an ODF row with numeric cells carrying both values and display text.""" - marked = f' table:style-name="{style}"' if style else "" - out = [" "] - for cell in cells: - if isinstance(cell, int): - out.append( - f' ' - f"{cell}" - ) - else: - out.append( - f' ' - f"{escape(cell)}" - ) - out.append(" ") - - return "\n".join(out) - - -# The head and the totals row, which the report and the sheet mark the same way. -CELL_STYLES = """ - - - - - - - """ % (RULE, ACCENT, RULE) - - -def sheet(words: dict) -> str: - """Two sheets, so the tab bar under the document has something to show.""" - automatic = "\n".join( - [ - # two widths: eight at the label's width put half the sheet off - # the right edge, and a figure needs less room than its row's name - """ - - """, - """ - - """, - CELL_STYLES, - ] - ) - - head, body, foot = table(words, columns=6) - - overview = [odf_row(head, "ceHead")] + [odf_row(line) for line in body] + [odf_row(foot, "ceTotal")] - costs = [odf_row([words["item"], words["total"]], "ceHead")] - costs += [odf_row([line[0], line[-1]]) for line in body] - tables = [] - for name, rows, columns in ( - (words["sheets"][0], overview, len(head)), - (words["sheets"][1], costs, 2), - ): - # the label column, then a figure column for each of the rest - marks = "\n".join( - [' '] - + [' '] * (columns - 1) - ) - tables.append( - f' \n{marks}\n' - + "\n".join(rows) - + "\n " - ) - - return content(" \n" + "\n".join(tables) + "\n ", automatic) - - -def deck(words: dict) -> str: - """Three slides, each with a title and its bullets.""" - automatic = "\n".join( - [ - paragraph_style("SlideTitle", size="32pt", weight="bold", colour=ACCENT, space="0.6cm"), - paragraph_style("Bullet", size="18pt", space="0.35cm"), - ] - ) - - pages = [] - for title, bullets in words["slides"]: - lines = [f' {escape(title)}'] - lines += [ - f' • {escape(point)}' for point in bullets - ] - pages.append( - f' \n' - ' \n' - " \n" + "\n".join(lines) + "\n \n" - " \n " - ) - - return content(" \n" + "\n".join(pages) + "\n ", automatic) - - -# Short and plain on purpose: this is a document over someone's shoulder in a -# store screenshot, not copy that has to sell anything. -WORDS = { - "en": { - "title": "Quarterly report", - "lead": "The team met every goal of the second quarter, and the new release went out on time.", - "sections": [ - ["Highlights", [ - "Costs stayed below budget, and two new partners joined the project.", - "The new release reached more people in its first week than the last one did in a month.", - "Support answered nine of ten questions the same day.",]], - ["Costs and budget", [ - "Spending on software rose with the new licences, while travel fell again.", - "Hardware was replaced once, and support stayed steady through the quarter.", - "Two servers moved to the new provider without a day of downtime.",]], - ["Next quarter", [ - "The release in September is the last one planned this year.", - "Two positions open in support, and one in design.", - "The office moves in November, and the budget for it is agreed.", - ]], - ["The people", [ - "Six people worked on the release, two of them new this year.", - "Holiday cover was arranged in April and held through the summer.", - "Everyone has taken the training the new licence requires.", - ]], - ["Risks", [ - "The move in November is the one date nothing else can slip past.", - "One supplier has not signed the new terms, and is being chased.", - "Hosting costs rise in January unless the contract is renewed early.", - ]], - ], - "closing": "The next meeting is at the end of July.", - "sheets": ["Overview", "Costs"], - "item": "Item", - "total": "Total", - "periods": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], - "rows": ["Software", "Travel", "Hardware", "Marketing", "Support", "Training", "Licences", "Hosting", "Events", "Office", "Cloud", "Recruiting", "Legal", "Insurance", "Catering", "Shipping", "Advertising", "Consulting", "Maintenance", "Utilities", "Equipment", "Subscriptions", "Telephony", "Internet", "Security", "Backups", "Domains", "Certificates", "Printing", "Stationery", "Postage", "Cleaning", "Repairs", "Furniture", "Storage", "Bank fees", "Memberships", "Conferences", "Translation", "Design"], - "slides": [ - ["Project plan", ["Goals for the quarter", "Budget and costs", "Next steps"]], - ["Schedule", ["Release in June", "Review in July", "Planning in August"]], - ["Team", ["Two new partners", "Support in three languages", "Training in autumn"]], - ], - }, - "de": { - "title": "Quartalsbericht", - "lead": "Das Team hat alle Ziele des zweiten Quartals erreicht, und die neue Version ist pünktlich erschienen.", - "sections": [ - ["Das Wichtigste", [ - "Die Kosten blieben unter dem Budget, und zwei neue Partner sind zum Projekt gestoßen.", - "Die neue Version erreichte in der ersten Woche mehr Menschen als die letzte in einem Monat.", - "Der Support beantwortete neun von zehn Anfragen noch am selben Tag.",]], - ["Kosten und Budget", [ - "Die Ausgaben für Software stiegen mit den neuen Lizenzen, die Reisekosten sanken erneut.", - "Die Hardware wurde einmal ersetzt, der Support blieb das ganze Quartal über stabil.", - "Zwei Server sind ohne einen Tag Ausfall zum neuen Anbieter umgezogen.",]], - ["Nächstes Quartal", [ - "Die Version im September ist die letzte für dieses Jahr.", - "Zwei Stellen im Support sind offen, eine im Design.", - "Der Umzug ins neue Büro ist für November geplant und budgetiert.", - ]], - ["Das Team", [ - "An der Version arbeiteten sechs Personen, zwei davon neu in diesem Jahr.", - "Die Urlaubsvertretung wurde im April geregelt und hat den ganzen Sommer über gehalten.", - "Alle haben die Schulung absolviert, die die neue Lizenz verlangt.", - ]], - ["Risiken", [ - "Der Umzug im November ist der einzige Termin, der sich nicht verschieben lässt.", - "Ein Lieferant hat die neuen Bedingungen noch nicht unterschrieben; wir haken nach.", - "Die Hostingkosten steigen im Januar, wenn der Vertrag nicht vorzeitig verlängert wird.", - ]], - ], - "closing": "Das nächste Treffen findet Ende Juli statt.", - "sheets": ["Übersicht", "Kosten"], - "item": "Position", - "total": "Gesamt", - "periods": ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun"], - "rows": ["Software", "Reisen", "Hardware", "Marketing", "Support", "Schulung", "Lizenzen", "Hosting", "Veranstaltungen", "Büro", "Cloud", "Personalsuche", "Recht", "Versicherung", "Verpflegung", "Versand", "Werbung", "Beratung", "Wartung", "Nebenkosten", "Ausstattung", "Abonnements", "Telefonie", "Internet", "Sicherheit", "Backups", "Domains", "Zertifikate", "Druck", "Büromaterial", "Porto", "Reinigung", "Reparaturen", "Möbel", "Lager", "Bankgebühren", "Mitgliedschaften", "Konferenzen", "Übersetzung", "Design"], - "slides": [ - ["Projektplan", ["Ziele für das Quartal", "Budget und Kosten", "Nächste Schritte"]], - ["Zeitplan", ["Version im Juni", "Rückblick im Juli", "Planung im August"]], - ["Team", ["Zwei neue Partner", "Support in drei Sprachen", "Schulung im Herbst"]], - ], - }, - "es": { - "title": "Informe trimestral", - "lead": "El equipo cumplió todos los objetivos del segundo trimestre y la nueva versión salió a tiempo.", - "sections": [ - ["Lo más destacado", [ - "Los costes se mantuvieron por debajo del presupuesto y dos nuevos socios se unieron al proyecto.", - "La nueva versión llegó a más gente en su primera semana que la anterior en un mes.", - "El soporte respondió nueve de cada diez consultas el mismo día.",]], - ["Costes y presupuesto", [ - "El gasto en software subió con las nuevas licencias, mientras que los viajes volvieron a bajar.", - "El hardware se sustituyó una vez y el soporte se mantuvo estable durante el trimestre.", - "Dos servidores pasaron al nuevo proveedor sin una sola interrupción del servicio.",]], - ["Próximo trimestre", [ - "La versión de septiembre es la última prevista este año.", - "Hay dos vacantes en soporte y una en diseño.", - "La mudanza de oficina es en noviembre y ya tiene presupuesto.", - ]], - ["Las personas", [ - "En la versión trabajaron seis personas, dos de ellas nuevas este año.", - "La cobertura de vacaciones se organizó en abril y aguantó todo el verano.", - "Todos han hecho la formación que exige la nueva licencia.", - ]], - ["Riesgos", [ - "La mudanza de noviembre es la única fecha que no puede moverse.", - "Un proveedor aún no ha firmado las nuevas condiciones y se le está reclamando.", - "El alojamiento sube en enero si no se renueva antes el contrato.", - ]], - ], - "closing": "La próxima reunión es a finales de julio.", - "sheets": ["Resumen", "Costes"], - "item": "Concepto", - "total": "Total", - "periods": ["Ene", "Feb", "Mar", "Abr", "May", "Jun"], - "rows": ["Software", "Viajes", "Hardware", "Marketing", "Soporte", "Formación", "Licencias", "Alojamiento", "Eventos", "Oficina", "Nube", "Contratación", "Legal", "Seguros", "Catering", "Envíos", "Publicidad", "Consultoría", "Mantenimiento", "Suministros", "Equipamiento", "Suscripciones", "Telefonía", "Internet", "Seguridad", "Copias de seguridad", "Dominios", "Certificados", "Impresión", "Papelería", "Franqueo", "Limpieza", "Reparaciones", "Mobiliario", "Almacenamiento", "Comisiones bancarias", "Cuotas", "Congresos", "Traducción", "Diseño"], - "slides": [ - ["Plan del proyecto", ["Objetivos del trimestre", "Presupuesto y costes", "Próximos pasos"]], - ["Calendario", ["Versión en junio", "Revisión en julio", "Planificación en agosto"]], - ["Equipo", ["Dos nuevos socios", "Soporte en tres idiomas", "Formación en otoño"]], - ], - }, - "fr": { - "title": "Rapport trimestriel", - "lead": "L'équipe a atteint tous les objectifs du deuxième trimestre et la nouvelle version est sortie à temps.", - "sections": [ - ["Points forts", [ - "Les coûts sont restés dans le budget et deux nouveaux partenaires ont rejoint le projet.", - "La nouvelle version a touché plus de monde en une semaine que la précédente en un mois.", - "Le support a répondu à neuf demandes sur dix le jour même.",]], - ["Coûts et budget", [ - "Les dépenses en logiciels ont augmenté avec les nouvelles licences, tandis que les déplacements ont encore baissé.", - "Le matériel a été remplacé une fois et le support est resté stable sur le trimestre.", - "Deux serveurs ont migré vers le nouveau prestataire sans la moindre interruption de service.",]], - ["Trimestre prochain", [ - "La version de septembre est la dernière prévue cette année.", - "Deux postes sont ouverts au support, un au design.", - "Le déménagement est prévu en novembre, et le budget est validé.", - ]], - ["Les personnes", [ - "Six personnes ont travaillé sur la version, dont deux arrivées cette année.", - "Les remplacements pour les congés ont été organisés en avril et ont tenu tout l'été.", - "Tout le monde a suivi la formation qu'exige la nouvelle licence.", - ]], - ["Risques", [ - "Le déménagement de novembre est la seule date qui ne peut pas bouger.", - "Un prestataire n'a pas encore signé les nouvelles conditions.", - "Le coût de l'hébergement augmente en janvier sans renouvellement anticipé.", - ]], - ], - "closing": "La prochaine réunion aura lieu fin juillet.", - "sheets": ["Aperçu", "Coûts"], - "item": "Poste", - "total": "Total", - "periods": ["Janv.", "Févr.", "Mars", "Avr.", "Mai", "Juin"], - "rows": ["Logiciels", "Déplacements", "Matériel", "Marketing", "Support", "Formation", "Licences", "Hébergement", "Événements", "Bureau", "Cloud", "Recrutement", "Juridique", "Assurance", "Traiteur", "Expédition", "Publicité", "Conseil", "Maintenance", "Charges", "Équipement", "Abonnements", "Téléphonie", "Internet", "Sécurité", "Sauvegardes", "Domaines", "Certificats", "Impression", "Fournitures", "Affranchissement", "Nettoyage", "Réparations", "Mobilier", "Stockage", "Frais bancaires", "Cotisations", "Conférences", "Traduction", "Design"], - "slides": [ - ["Plan du projet", ["Objectifs du trimestre", "Budget et coûts", "Prochaines étapes"]], - ["Calendrier", ["Version en juin", "Bilan en juillet", "Planification en août"]], - ["Équipe", ["Deux nouveaux partenaires", "Support en trois langues", "Formation à l'automne"]], - ], - }, - "it": { - "title": "Relazione trimestrale", - "lead": "Il team ha raggiunto tutti gli obiettivi del secondo trimestre e la nuova versione è uscita in tempo.", - "sections": [ - ["In evidenza", [ - "I costi sono rimasti sotto il budget e due nuovi partner si sono uniti al progetto.", - "La nuova versione ha raggiunto in una settimana più persone di quante ne avesse raggiunte la precedente in un mese.", - "Il supporto ha risposto a nove richieste su dieci in giornata.",]], - ["Costi e budget", [ - "La spesa per il software è cresciuta con le nuove licenze, mentre quella per i viaggi è di nuovo calata.", - "L'hardware è stato sostituito una volta e il supporto è rimasto stabile per tutto il trimestre.", - "Due server sono passati al nuovo fornitore senza un giorno di fermo.",]], - ["Prossimo trimestre", [ - "La versione di settembre è l'ultima prevista quest'anno.", - "Ci sono due posizioni aperte nel supporto e una nel design.", - "Il trasloco è a novembre e il budget è approvato.", - ]], - ["Le persone", [ - "Alla versione hanno lavorato sei persone, due delle quali nuove quest'anno.", - "Le sostituzioni estive sono state organizzate ad aprile e hanno retto.", - "Tutti hanno seguito il corso richiesto dalla nuova licenza.", - ]], - ["Rischi", [ - "Il trasloco di novembre è l'unica data che non può slittare.", - "Un fornitore non ha ancora firmato le nuove condizioni.", - "I costi di hosting aumentano a gennaio se il contratto non viene rinnovato in anticipo.", - ]], - ], - "closing": "Il prossimo incontro è a fine luglio.", - "sheets": ["Panoramica", "Costi"], - "item": "Voce", - "total": "Totale", - "periods": ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu"], - "rows": ["Software", "Viaggi", "Hardware", "Marketing", "Supporto", "Formazione", "Licenze", "Hosting", "Eventi", "Ufficio", "Cloud", "Selezione", "Legale", "Assicurazione", "Catering", "Spedizioni", "Pubblicità", "Consulenza", "Manutenzione", "Utenze", "Attrezzature", "Abbonamenti", "Telefonia", "Internet", "Sicurezza", "Backup", "Domini", "Certificati", "Stampa", "Cancelleria", "Affrancature", "Pulizie", "Riparazioni", "Arredi", "Archiviazione", "Spese bancarie", "Quote associative", "Conferenze", "Traduzioni", "Design"], - "slides": [ - ["Piano di progetto", ["Obiettivi del trimestre", "Budget e costi", "Prossimi passi"]], - ["Calendario", ["Versione a giugno", "Revisione a luglio", "Pianificazione ad agosto"]], - ["Team", ["Due nuovi partner", "Supporto in tre lingue", "Formazione in autunno"]], - ], - }, - "pl": { - "title": "Raport kwartalny", - "lead": "Zespół osiągnął wszystkie cele drugiego kwartału, a nowa wersja ukazała się na czas.", - "sections": [ - ["Najważniejsze", [ - "Koszty pozostały poniżej budżetu, a do projektu dołączyło dwóch nowych partnerów.", - "Nowa wersja dotarła w pierwszym tygodniu do większej liczby osób niż poprzednia w miesiąc.", - "Wsparcie odpowiedziało na dziewięć z dziesięciu zgłoszeń tego samego dnia.",]], - ["Koszty i budżet", [ - "Wydatki na oprogramowanie wzrosły wraz z nowymi licencjami, a koszty podróży znów spadły.", - "Sprzęt wymieniono raz, a wsparcie było stabilne przez cały kwartał.", - "Dwa serwery przeniesiono do nowego dostawcy bez ani jednego dnia przestoju.",]], - ["Następny kwartał", [ - "Wersja z września jest ostatnią zaplanowaną w tym roku.", - "Otwarte są dwa etaty we wsparciu i jeden w dziale projektowym.", - "Przeprowadzka biura wypada w listopadzie i ma już budżet.", - ]], - ["Ludzie", [ - "Nad wersją pracowało sześć osób, z czego dwie dołączyły w tym roku.", - "Zastępstwa urlopowe ustalono w kwietniu i utrzymały się przez całe lato.", - "Wszyscy przeszli szkolenie wymagane przez nową licencję.", - ]], - ["Ryzyka", [ - "Przeprowadzka w listopadzie to jedyny termin, który nie może się przesunąć.", - "Jeden dostawca nie podpisał jeszcze nowych warunków i jest ponaglany.", - "Koszty hostingu wzrosną w styczniu, jeśli umowa nie zostanie odnowiona wcześniej.", - ]], - ], - "closing": "Następne spotkanie odbędzie się pod koniec lipca.", - "sheets": ["Przegląd", "Koszty"], - "item": "Pozycja", - "total": "Razem", - "periods": ["sty", "lut", "mar", "kwi", "maj", "cze"], - "rows": ["Oprogramowanie", "Podróże", "Sprzęt", "Marketing", "Wsparcie", "Szkolenia", "Licencje", "Hosting", "Wydarzenia", "Biuro", "Chmura", "Rekrutacja", "Prawo", "Ubezpieczenie", "Catering", "Wysyłka", "Reklama", "Doradztwo", "Utrzymanie", "Media", "Wyposażenie", "Subskrypcje", "Telefonia", "Internet", "Bezpieczeństwo", "Kopie zapasowe", "Domeny", "Certyfikaty", "Druk", "Artykuły biurowe", "Opłaty pocztowe", "Sprzątanie", "Naprawy", "Meble", "Magazyn", "Opłaty bankowe", "Składki członkowskie", "Konferencje", "Tłumaczenia", "Projektowanie"], - "slides": [ - ["Plan projektu", ["Cele na kwartał", "Budżet i koszty", "Kolejne kroki"]], - ["Harmonogram", ["Wersja w czerwcu", "Podsumowanie w lipcu", "Planowanie w sierpniu"]], - ["Zespół", ["Dwóch nowych partnerów", "Wsparcie w trzech językach", "Szkolenia jesienią"]], - ], - }, - "pt-BR": { - "title": "Relatório trimestral", - "lead": "A equipe alcançou todas as metas do segundo trimestre e a nova versão saiu no prazo.", - "sections": [ - ["Destaques", [ - "Os custos ficaram abaixo do orçamento e dois novos parceiros entraram no projeto.", - "A nova versão alcançou mais pessoas na primeira semana do que a anterior em um mês.", - "O suporte respondeu nove de cada dez chamados no mesmo dia.",]], - ["Custos e orçamento", [ - "Os gastos com software subiram com as novas licenças, enquanto as viagens caíram de novo.", - "O hardware foi substituído uma vez e o suporte se manteve estável no trimestre.", - "Dois servidores migraram para o novo provedor sem um dia de indisponibilidade.",]], - ["Próximo trimestre", [ - "A versão de setembro é a última prevista para este ano.", - "Há duas vagas no suporte e uma no design.", - "A mudança de escritório é em novembro e já tem orçamento.", - ]], - ["As pessoas", [ - "Seis pessoas trabalharam na versão, duas delas novas este ano.", - "A escala de férias foi definida em abril e valeu o verão todo.", - "Todos fizeram o treinamento que a nova licença exige.", - ]], - ["Riscos", [ - "A mudança de novembro é a única data que não pode atrasar.", - "Um fornecedor ainda não assinou as novas condições.", - "A hospedagem sobe em janeiro se o contrato não for renovado antes.", - ]], - ], - "closing": "A próxima reunião é no fim de julho.", - "sheets": ["Visão geral", "Custos"], - "item": "Item", - "total": "Total", - "periods": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun"], - "rows": ["Software", "Viagens", "Hardware", "Marketing", "Suporte", "Treinamento", "Licenças", "Hospedagem", "Eventos", "Escritório", "Nuvem", "Recrutamento", "Jurídico", "Seguros", "Buffet", "Frete", "Publicidade", "Consultoria", "Manutenção", "Água e luz", "Equipamentos", "Assinaturas", "Telefonia", "Internet", "Segurança", "Backups", "Domínios", "Certificados", "Impressão", "Papelaria", "Correios", "Limpeza", "Reparos", "Móveis", "Armazenamento", "Tarifas bancárias", "Associações", "Conferências", "Tradução", "Design"], - "slides": [ - ["Plano do projeto", ["Metas do trimestre", "Orçamento e custos", "Próximos passos"]], - ["Cronograma", ["Versão em junho", "Revisão em julho", "Planejamento em agosto"]], - ["Equipe", ["Dois novos parceiros", "Suporte em três idiomas", "Treinamento no outono"]], - ], - }, - "ru": { - "title": "Квартальный отчёт", - "lead": "Команда достигла всех целей второго квартала, и новая версия вышла в срок.", - "sections": [ - ["Главное", [ - "Расходы остались в рамках бюджета, а к проекту присоединились два новых партнёра.", - "За первую неделю новая версия охватила больше людей, чем предыдущая за месяц.", - "Поддержка ответила на девять из десяти обращений в тот же день.",]], - ["Расходы и бюджет", [ - "Затраты на ПО выросли из-за новых лицензий, а расходы на поездки снова снизились.", - "Оборудование меняли один раз, поддержка работала стабильно весь квартал.", - "Два сервера переехали к новому провайдеру без единого дня простоя.",]], - ["Следующий квартал", [ - "Версия в сентябре — последняя из запланированных в этом году.", - "Открыты две вакансии в поддержке и одна в дизайне.", - "Переезд офиса намечен на ноябрь, бюджет утверждён.", - ]], - ["Люди", [ - "Над версией работали шесть человек, двое из них пришли в этом году.", - "Замены на время отпусков согласовали в апреле, и график продержался всё лето.", - "Все прошли обучение, которого требует новая лицензия.", - ]], - ["Риски", [ - "Переезд в ноябре — единственная дата, которую нельзя сдвинуть.", - "Один поставщик так и не подписал новые условия, ему напоминают.", - "Хостинг подорожает в январе, если не продлить договор заранее.", - ]], - ], - "closing": "Следующая встреча — в конце июля.", - "sheets": ["Обзор", "Расходы"], - "item": "Статья", - "total": "Итого", - "periods": ["Янв.", "Февр.", "Март", "Апр.", "Май", "Июнь"], - "rows": ["ПО", "Поездки", "Оборудование", "Маркетинг", "Поддержка", "Обучение", "Лицензии", "Хостинг", "Мероприятия", "Офис", "Облако", "Наём", "Юристы", "Страхование", "Кейтеринг", "Доставка", "Реклама", "Консалтинг", "Обслуживание", "Коммунальные услуги", "Оснащение", "Подписки", "Телефония", "Интернет", "Безопасность", "Резервное копирование", "Домены", "Сертификаты", "Печать", "Канцтовары", "Почтовые расходы", "Уборка", "Ремонт", "Мебель", "Хранение", "Банковские комиссии", "Членские взносы", "Конференции", "Перевод", "Дизайн"], - "slides": [ - ["План проекта", ["Цели на квартал", "Бюджет и расходы", "Следующие шаги"]], - ["График", ["Версия в июне", "Итоги в июле", "Планирование в августе"]], - ["Команда", ["Два новых партнёра", "Поддержка на трёх языках", "Обучение осенью"]], - ], - }, - "tr": { - "title": "Üç aylık rapor", - "lead": "Ekip ikinci çeyreğin tüm hedeflerine ulaştı ve yeni sürüm zamanında yayınlandı.", - "sections": [ - ["Öne çıkanlar", [ - "Maliyetler bütçenin altında kaldı ve projeye iki yeni ortak katıldı.", - "Yeni sürüm ilk haftasında, öncekinin bir ayda ulaştığından daha fazla kişiye ulaştı.", - "Destek, on sorudan dokuzunu aynı gün yanıtladı.",]], - ["Maliyetler ve bütçe", [ - "Yeni lisanslarla yazılım harcamaları arttı, seyahat giderleri yeniden düştü.", - "Donanım bir kez yenilendi ve destek çeyrek boyunca istikrarlı kaldı.", - "İki sunucu, bir gün bile kesinti olmadan yeni sağlayıcıya taşındı.",]], - ["Gelecek çeyrek", [ - "Eylüldeki sürüm bu yıl planlanan son sürüm.", - "Destekte iki, tasarımda bir pozisyon açık.", - "Ofis taşınması kasımda ve bütçesi onaylandı.", - ]], - ["Ekip", [ - "Sürüm üzerinde altı kişi çalıştı, ikisi bu yıl katıldı.", - "İzin dönemi vekaletleri nisanda belirlendi ve yaz boyunca sorunsuz işledi.", - "Herkes yeni lisansın gerektirdiği eğitimi tamamladı.", - ]], - ["Riskler", [ - "Kasımdaki taşınma, ertelenemeyecek tek tarih.", - "Bir tedarikçi yeni koşulları henüz imzalamadı, takibi sürüyor.", - "Sözleşme erken yenilenmezse barındırma maliyeti ocakta artacak.", - ]], - ], - "closing": "Bir sonraki toplantı temmuz sonunda.", - "sheets": ["Genel bakış", "Maliyetler"], - "item": "Kalem", - "total": "Toplam", - "periods": ["Oca", "Şub", "Mar", "Nis", "May", "Haz"], - "rows": ["Yazılım", "Seyahat", "Donanım", "Pazarlama", "Destek", "Eğitim", "Lisanslar", "Barındırma", "Etkinlikler", "Ofis", "Bulut", "İşe alım", "Hukuk", "Sigorta", "İkram", "Kargo", "Reklam", "Danışmanlık", "Bakım", "Faturalar", "Ekipman", "Abonelikler", "Telefon", "İnternet", "Güvenlik", "Yedekleme", "Alan adları", "Sertifikalar", "Baskı", "Kırtasiye", "Posta", "Temizlik", "Onarım", "Mobilya", "Depolama", "Banka masrafları", "Üyelikler", "Konferanslar", "Çeviri", "Tasarım"], - "slides": [ - ["Proje planı", ["Çeyrek hedefleri", "Bütçe ve maliyetler", "Sonraki adımlar"]], - ["Takvim", ["Haziranda sürüm", "Temmuzda değerlendirme", "Ağustosta planlama"]], - ["Ekip", ["İki yeni ortak", "Üç dilde destek", "Sonbaharda eğitim"]], - ], - }, -} - -# Forty rows across six periods; other formats reuse smaller slices. -FIGURES = [ - [1200, 1450, 1310, 1600, 1380, 1520], - [480, 620, 510, 470, 690, 540], - [3600, 900, 1200, 750, 830, 1150], - [820, 760, 930, 1010, 870, 940], - [540, 560, 580, 600, 610, 630], - [300, 450, 380, 520, 410, 470], - [1100, 1150, 1180, 1240, 1260, 1290], - [640, 640, 660, 680, 700, 700], - [420, 980, 350, 610, 1240, 380], - [260, 280, 270, 300, 290, 310], - [890, 910, 940, 980, 1000, 1030], - [1500, 400, 620, 350, 480, 390], - [340, 360, 350, 370, 380, 390], - [220, 220, 230, 230, 240, 240], - [180, 620, 210, 240, 190, 660], - [410, 430, 400, 450, 440, 460], - [760, 820, 690, 900, 850, 780], - [950, 480, 1100, 520, 560, 1180], - [280, 290, 300, 310, 320, 330], - [520, 540, 530, 560, 570, 590], - [1340, 1290, 1410, 1360, 1440, 1480], - [710, 730, 720, 750, 760, 780], - [190, 200, 190, 210, 200, 220], - [330, 330, 340, 340, 350, 350], - [860, 890, 1240, 910, 930, 960], - [240, 250, 260, 260, 270, 280], - [120, 130, 120, 140, 130, 150], - [460, 170, 180, 490, 180, 190], - [580, 610, 550, 640, 600, 670], - [150, 160, 170, 160, 180, 170], - [210, 230, 220, 250, 240, 260], - [390, 390, 400, 410, 410, 420], - [270, 1080, 310, 340, 290, 360], - [1620, 350, 380, 360, 400, 370], - [620, 650, 630, 680, 660, 700], - [110, 120, 110, 130, 120, 140], - [440, 450, 460, 470, 480, 490], - [980, 1020, 640, 1060, 1090, 720], - [560, 500, 590, 530, 610, 570], - [740, 770, 800, 790, 830, 860], -] - -# Localized sample filenames. -FILE_NAMES = { - "en": {"text": "Quarterly report", "sheet": "Budget", "slides": "Project plan", - "word": "Contract", "cells": "Sales figures", "deck": "Team offsite", - "paper": "Invoice", "rows": "Contacts", "notes": "Notes"}, - "de": {"text": "Quartalsbericht", "sheet": "Budget", "slides": "Projektplan", - "word": "Vertrag", "cells": "Umsatzzahlen", "deck": "Teamtreffen", - "paper": "Rechnung", "rows": "Kontakte", "notes": "Notizen"}, - "es": {"text": "Informe trimestral", "sheet": "Presupuesto", "slides": "Plan del proyecto", - "word": "Contrato", "cells": "Cifras de ventas", "deck": "Jornada de equipo", - "paper": "Factura", "rows": "Contactos", "notes": "Notas"}, - "fr": {"text": "Rapport trimestriel", "sheet": "Budget", "slides": "Plan du projet", - "word": "Contrat", "cells": "Chiffres des ventes", "deck": "Réunion d'équipe", - "paper": "Facture", "rows": "Contacts", "notes": "Notes"}, - "it": {"text": "Relazione trimestrale", "sheet": "Budget", "slides": "Piano di progetto", - "word": "Contratto", "cells": "Dati di vendita", "deck": "Ritiro del team", - "paper": "Fattura", "rows": "Contatti", "notes": "Note"}, - "pl": {"text": "Raport kwartalny", "sheet": "Budżet", "slides": "Plan projektu", - "word": "Umowa", "cells": "Wyniki sprzedaży", "deck": "Spotkanie zespołu", - "paper": "Faktura", "rows": "Kontakty", "notes": "Notatki"}, - "pt-BR": {"text": "Relatório trimestral", "sheet": "Orçamento", "slides": "Plano do projeto", - "word": "Contrato", "cells": "Números de vendas", "deck": "Reunião da equipe", - "paper": "Fatura", "rows": "Contatos", "notes": "Notas"}, - "ru": {"text": "Квартальный отчёт", "sheet": "Бюджет", "slides": "План проекта", - "word": "Договор", "cells": "Продажи", "deck": "Встреча команды", - "paper": "Счёт", "rows": "Контакты", "notes": "Заметки"}, - "tr": {"text": "Üç aylık rapor", "sheet": "Bütçe", "slides": "Proje planı", - "word": "Sözleşme", "cells": "Satış rakamları", "deck": "Ekip çalıştayı", - "paper": "Fatura", "rows": "Kişiler", "notes": "Notlar"}, -} - -# Extra browser entries copy existing samples and are never opened. -FILLERS = { - "meeting": "text", - "letter": "text", - "travel": "text", - "reading": "text", - "household": "sheet", - "hours": "sheet", - "stocktake": "sheet", - "kickoff": "slides", - "course": "slides", - "lease": "word", - "resume": "word", - "application": "word", - "expenses": "cells", - "inventory": "cells", - "review": "deck", - "ticket": "paper", - "warranty": "paper", - "manual": "paper", -} - -# A language with none of its own falls back to English. -FILLER_NAMES = { - "en": { - "meeting": "Meeting notes", "letter": "Letter to the landlord", - "travel": "Travel plan", "reading": "Reading list", - "household": "Household budget", "hours": "Hours", "stocktake": "Stocktake", - "kickoff": "Kickoff", "course": "Course slides", - "lease": "Lease", "resume": "CV", "application": "Application", - "expenses": "Expenses", "inventory": "Inventory", - "review": "Quarterly review", - "ticket": "Ticket", "warranty": "Warranty", "manual": "Manual", - }, - "de": { - "meeting": "Besprechungsnotizen", "letter": "Brief an den Vermieter", - "travel": "Reiseplan", "reading": "Leseliste", - "household": "Haushaltsbudget", "hours": "Arbeitszeiten", "stocktake": "Inventur", - "kickoff": "Auftakt", "course": "Kursfolien", - "lease": "Mietvertrag", "resume": "Lebenslauf", "application": "Bewerbung", - "expenses": "Ausgaben", "inventory": "Bestand", - "review": "Quartalsrückblick", - "ticket": "Ticket", "warranty": "Garantie", "manual": "Anleitung", - }, - "es": { - "meeting": "Notas de reunión", "letter": "Carta al casero", - "travel": "Plan de viaje", "reading": "Lista de lectura", - "household": "Presupuesto doméstico", "hours": "Horas", "stocktake": "Recuento", - "kickoff": "Arranque del proyecto", "course": "Diapositivas del curso", - "lease": "Alquiler del piso", "resume": "Currículum", "application": "Solicitud", - "expenses": "Gastos", "inventory": "Inventario", - "review": "Revisión trimestral", - "ticket": "Billete", "warranty": "Garantía", "manual": "Manual", - }, - "fr": { - "meeting": "Notes de réunion", "letter": "Lettre au propriétaire", - "travel": "Itinéraire", "reading": "Liste de lecture", - "household": "Budget familial", "hours": "Heures", "stocktake": "Inventaire", - "kickoff": "Lancement", "course": "Diapositives du cours", - "lease": "Bail", "resume": "CV", "application": "Candidature", - "expenses": "Dépenses", "inventory": "Stock", - "review": "Bilan trimestriel", - "ticket": "Billet", "warranty": "Garantie", "manual": "Manuel", - }, - "it": { - "meeting": "Note della riunione", "letter": "Lettera al locatore", - "travel": "Piano di viaggio", "reading": "Lista di lettura", - "household": "Bilancio familiare", "hours": "Ore", "stocktake": "Inventario", - "kickoff": "Avvio", "course": "Diapositive del corso", - "lease": "Contratto d'affitto", "resume": "Curriculum", "application": "Candidatura", - "expenses": "Spese", "inventory": "Magazzino", - "review": "Revisione trimestrale", - "ticket": "Biglietto", "warranty": "Garanzia", "manual": "Manuale", - }, - "pl": { - "meeting": "Notatki ze spotkania", "letter": "List do właściciela mieszkania", - "travel": "Plan podróży", "reading": "Lista lektur", - "household": "Budżet domowy", "hours": "Godziny", "stocktake": "Inwentaryzacja", - "kickoff": "Spotkanie startowe", "course": "Slajdy kursu", - "lease": "Umowa najmu", "resume": "CV", "application": "Podanie", - "expenses": "Wydatki", "inventory": "Stan magazynu", - "review": "Przegląd kwartalny", - "ticket": "Bilet", "warranty": "Gwarancja", "manual": "Instrukcja", - }, - "pt-BR": { - "meeting": "Notas da reunião", "letter": "Carta ao locador", - "travel": "Plano de viagem", "reading": "Lista de leitura", - "household": "Orçamento doméstico", "hours": "Horas", "stocktake": "Balanço", - "kickoff": "Kickoff", "course": "Slides do curso", - "lease": "Contrato de aluguel", "resume": "Currículo", "application": "Inscrição", - "expenses": "Despesas", "inventory": "Estoque", - "review": "Revisão trimestral", - "ticket": "Passagem", "warranty": "Garantia", "manual": "Manual", - }, - "ru": { - "meeting": "Заметки со встречи", - "letter": "Письмо арендодателю", - "travel": "План поездки", - "reading": "Список чтения", - "household": "Домашний бюджет", - "hours": "Часы", - "stocktake": "Инвентаризация", - "kickoff": "Старт проекта", - "course": "Слайды курса", - "lease": "Договор аренды", - "resume": "Резюме", - "application": "Заявление", - "expenses": "Расходы", - "inventory": "Склад", - "review": "Квартальный обзор", - "ticket": "Билет", - "warranty": "Гарантия", - "manual": "Инструкция", - }, - "tr": { - "meeting": "Toplantı notları", "letter": "Ev sahibine mektup", - "travel": "Seyahat planı", "reading": "Okuma listesi", - "household": "Ev bütçesi", "hours": "Çalışma saatleri", - "stocktake": "Sayım", - "kickoff": "Proje başlangıcı", "course": "Kurs slaytları", - "lease": "Kira sözleşmesi", "resume": "Özgeçmiş", - "application": "Başvuru", - "expenses": "Giderler", "inventory": "Envanter", - "review": "Üç aylık değerlendirme", - "ticket": "Bilet", "warranty": "Garanti", "manual": "Kılavuz", - }, -} - - -# Choose a frequent long word for visible search matches. -def query(words: dict) -> str: - """The most repeated long word of the report, which is what to search for.""" - text = " ".join( - [words["title"], words["lead"], words["closing"]] - + [heading for heading, _ in words["sections"]] - + [line for _, paragraphs in words["sections"] for line in paragraphs] - ) - - counted = {} - for word in re.findall(r"\w+", text.lower(), flags=re.UNICODE): - if len(word) >= 5 and not word.isdigit(): - counted[word] = counted.get(word, 0) + 1 - - # the most repeated, and the longest of those, so the choice is not a coin toss - return max(counted, key=lambda word: (counted[word], len(word))) +def pinned() -> str: + """Return the sampledoc version requirements.txt pins.""" + for line in REQUIREMENTS.read_text(encoding="utf-8").splitlines(): + found = re.fullmatch(r"sampledoc==(\S+)", line.strip()) + if found: + return found.group(1) - -# Distinct sample content for each document format. -OTHERS = { - "en": { - "contract": ["Service agreement", - "This agreement is made between the two parties named below.", - ["The supplier provides the software described in the appendix for one year.", - "Payment is due within thirty days of each invoice.", - "Either party may end this agreement with three months' notice.", - "Changes to this agreement are valid only in writing.", - "The supplier keeps the service available on working days.", - "Both parties treat what they learn of each other as confidential.", - "Austrian law applies, and the court of Vienna has jurisdiction.", - "The supplier keeps a backup of the customer's data for thirty days.", - "Support requests are answered within one working day.", - "The customer names one person who may approve changes.", - "Prices hold for the first year and are reviewed each autumn.", - "Neither party may pass this agreement to a third party without consent.", - "The appendix lists the software covered and the version it starts at.", - "This agreement replaces every earlier arrangement between the parties."]], - "invoice": ["Invoice 2026-014", "Issued 12 June 2026", "Due within 30 days", "Billed to", "Subtotal", "VAT 20%", "Amount due", "Thank you for your business.", "Qty", "Unit price"], - "contacts": [["Name", "Team", "Email", "Phone"], - ["Design", "Support", "Sales", "Engineering"]], - }, - "de": { - "contract": ["Dienstleistungsvertrag", - "Dieser Vertrag wird zwischen den beiden unten genannten Parteien geschlossen.", - ["Der Anbieter stellt die im Anhang beschriebene Software für ein Jahr bereit.", - "Die Zahlung ist innerhalb von dreißig Tagen nach Rechnungsstellung fällig.", - "Beide Parteien können den Vertrag mit einer Frist von drei Monaten kündigen.", - "Änderungen dieses Vertrags bedürfen der Schriftform.", - "Der Anbieter hält den Dienst an Werktagen verfügbar.", - "Beide Parteien behandeln vertraulich, was sie voneinander erfahren.", - "Es gilt österreichisches Recht; Gerichtsstand ist Wien.", - "Der Anbieter bewahrt eine Sicherung der Daten des Kunden dreißig Tage lang auf.", - "Supportanfragen werden innerhalb eines Werktags beantwortet.", - "Der Kunde benennt eine Person, die Änderungen freigeben darf.", - "Die Preise gelten im ersten Jahr und werden jeden Herbst überprüft.", - "Keine Partei darf diesen Vertrag ohne Zustimmung an Dritte weitergeben.", - "Der Anhang nennt die erfasste Software und die Version, ab der sie gilt.", - "Dieser Vertrag ersetzt alle früheren Vereinbarungen zwischen den Parteien."]], - "invoice": ["Rechnung 2026-014", "Ausgestellt am 12. Juni 2026", "Zahlbar innerhalb von 30 Tagen", "Rechnung an", "Zwischensumme", "USt. 20%", "Zahlbetrag", "Vielen Dank für Ihren Auftrag.", "Menge", "Einzelpreis"], - "contacts": [["Name", "Team", "E-Mail", "Telefon"], - ["Design", "Support", "Vertrieb", "Entwicklung"]], - }, - "es": { - "contract": ["Contrato de servicios", - "Este contrato se celebra entre las dos partes indicadas a continuación.", - ["El proveedor facilita el software descrito en el anexo durante un año.", - "El pago vence a los treinta días de cada factura.", - "Cualquiera de las partes puede rescindirlo con tres meses de preaviso.", - "Las modificaciones solo son válidas por escrito.", - "El proveedor mantiene el servicio disponible los días laborables.", - "Ambas partes tratan como confidencial lo que conozcan de la otra.", - "Se aplica la ley austriaca y el tribunal de Viena es competente.", - "El proveedor conserva una copia de los datos del cliente durante treinta días.", - "Las consultas de soporte se responden en un día laborable.", - "El cliente designa a una persona que puede aprobar los cambios.", - "Los precios se mantienen el primer año y se revisan cada otoño.", - "Ninguna parte puede ceder este contrato a un tercero sin consentimiento.", - "El anexo enumera el software incluido y la versión desde la que se aplica.", - "Este contrato sustituye cualquier acuerdo anterior entre las partes."]], - "invoice": ["Factura 2026-014", "Emitida el 12 de junio de 2026", "Vence en 30 días", "Facturar a", "Subtotal", "IVA 20%", "Importe a pagar", "Gracias por su confianza.", "Cant.", "Precio unit."], - "contacts": [["Nombre", "Equipo", "Correo", "Teléfono"], - ["Diseño", "Soporte", "Ventas", "Ingeniería"]], - }, - "fr": { - "contract": ["Contrat de service", - "Ce contrat est conclu entre les deux parties désignées ci-dessous.", - ["Le prestataire fournit le logiciel décrit en annexe pendant un an.", - "Le paiement est dû dans les trente jours suivant chaque facture.", - "Chaque partie peut résilier le contrat avec un préavis de trois mois.", - "Toute modification n'est valable que par écrit.", - "Le prestataire maintient le service disponible les jours ouvrés.", - "Chaque partie traite comme confidentiel ce qu'elle apprend de l'autre.", - "Le droit autrichien s'applique et le tribunal de Vienne est compétent.", - "Le prestataire conserve une sauvegarde des données du client pendant trente jours.", - "Les demandes de support reçoivent une réponse sous un jour ouvré.", - "Le client désigne une personne habilitée à approuver les modifications.", - "Les prix sont fermes la première année et revus chaque automne.", - "Aucune des parties ne peut céder ce contrat à un tiers sans accord.", - "L'annexe indique le logiciel couvert et la version à partir de laquelle la couverture s'applique.", - "Ce contrat remplace tout accord antérieur entre les parties."]], - "invoice": ["Facture 2026-014", "Émise le 12 juin 2026", "À régler sous 30 jours", "Facturé à", "Sous-total", "TVA 20 %", "Montant dû", "Merci de votre confiance.", "Qté", "Prix unitaire"], - "contacts": [["Nom", "Équipe", "E-mail", "Téléphone"], - ["Design", "Support", "Ventes", "Développement"]], - }, - "it": { - "contract": ["Contratto di servizio", - "Il presente contratto è stipulato tra le due parti indicate di seguito.", - ["Il fornitore mette a disposizione per un anno il software descritto in allegato.", - "Il pagamento è dovuto entro trenta giorni da ogni fattura.", - "Ciascuna parte può recedere con un preavviso di tre mesi.", - "Le modifiche sono valide solo in forma scritta.", - "Il fornitore mantiene il servizio disponibile nei giorni lavorativi.", - "Le parti trattano come riservato quanto apprendono l'una dell'altra.", - "Si applica il diritto austriaco e il foro competente è Vienna.", - "Il fornitore conserva una copia dei dati del cliente per trenta giorni.", - "Le richieste di supporto ricevono risposta entro un giorno lavorativo.", - "Il cliente indica una persona autorizzata ad approvare le modifiche.", - "I prezzi restano fermi il primo anno e sono rivisti ogni autunno.", - "Nessuna parte può cedere il contratto a terzi senza consenso.", - "L'allegato elenca il software coperto e la versione di partenza.", - "Il presente contratto sostituisce ogni accordo precedente tra le parti."]], - "invoice": ["Fattura 2026-014", "Emessa il 12 giugno 2026", "Da saldare entro 30 giorni", "Intestato a", "Subtotale", "IVA 20%", "Importo dovuto", "Grazie per la collaborazione.", "Qtà", "Prezzo unit."], - "contacts": [["Nome", "Reparto", "E-mail", "Telefono"], - ["Design", "Supporto", "Vendite", "Sviluppo"]], - }, - "pl": { - "contract": ["Umowa o świadczenie usług", - "Niniejsza umowa zostaje zawarta między dwiema stronami wymienionymi poniżej.", - ["Dostawca udostępnia oprogramowanie opisane w załączniku na okres roku.", - "Płatność jest wymagalna w terminie trzydziestu dni od daty każdej faktury.", - "Każda ze stron może rozwiązać umowę z trzymiesięcznym wypowiedzeniem.", - "Zmiany umowy wymagają formy pisemnej.", - "Dostawca utrzymuje dostępność usługi w dni robocze.", - "Obie strony traktują jako poufne to, czego dowiedzą się o sobie nawzajem.", - "Obowiązuje prawo austriackie, a sądem właściwym jest sąd w Wiedniu.", - "Dostawca przechowuje kopię danych klienta przez trzydzieści dni.", - "Zgłoszenia do wsparcia są rozpatrywane w ciągu jednego dnia roboczego.", - "Klient wskazuje jedną osobę uprawnioną do zatwierdzania zmian.", - "Ceny obowiązują przez pierwszy rok i są weryfikowane każdej jesieni.", - "Żadna ze stron nie może przenieść umowy na osobę trzecią bez zgody.", - "Załącznik wymienia oprogramowanie objęte umową oraz wersję początkową.", - "Niniejsza umowa zastępuje wszystkie wcześniejsze ustalenia stron."]], - "invoice": ["Faktura 2026-014", "Wystawiono 12 czerwca 2026", "Płatne w ciągu 30 dni", "Nabywca", "Wartość netto", "VAT 20%", "Do zapłaty", "Dziękujemy za współpracę.", "Ilość", "Cena jedn."], - "contacts": [["Imię i nazwisko", "Dział", "E-mail", "Telefon"], - ["Projektowanie", "Wsparcie", "Sprzedaż", "Rozwój"]], - }, - "pt-BR": { - "contract": ["Contrato de serviço", - "Este contrato é celebrado entre as duas partes indicadas abaixo.", - ["O fornecedor disponibiliza por um ano o software descrito no anexo.", - "O pagamento vence em trinta dias a contar de cada fatura.", - "Qualquer parte pode encerrar o contrato com aviso prévio de três meses.", - "Alterações só são válidas por escrito.", - "O fornecedor mantém o serviço disponível em dias úteis.", - "As partes tratam como confidencial o que souberem uma da outra.", - "Aplica-se a lei austríaca e o foro competente é o de Viena.", - "O fornecedor mantém uma cópia dos dados do cliente por trinta dias.", - "Os chamados de suporte são respondidos em um dia útil.", - "O cliente indica uma pessoa autorizada a aprovar alterações.", - "Os preços ficam fixos no primeiro ano e são revisados todo outono.", - "Nenhuma parte pode transferir este contrato a terceiros sem consentimento.", - "O anexo lista o software abrangido e a versão inicial coberta.", - "Este contrato substitui qualquer acordo anterior entre as partes."]], - "invoice": ["Fatura 2026-014", "Emitida em 12 de junho de 2026", "Vence em 30 dias", "Faturado para", "Subtotal", "Impostos 20%", "Valor a pagar", "Obrigado pela preferência.", "Qtd", "Preço unit."], - "contacts": [["Nome", "Equipe", "E-mail", "Telefone"], - ["Design", "Suporte", "Vendas", "Engenharia"]], - }, - "ru": { - "contract": ["Договор оказания услуг", - "Настоящий договор заключён между двумя сторонами, указанными ниже.", - ["Исполнитель предоставляет программное обеспечение, указанное в приложении, сроком на один год.", - "Оплата производится в течение тридцати дней с даты счёта.", - "Каждая из сторон может расторгнуть договор, уведомив за три месяца.", - "Изменения действительны только в письменном виде.", - "Исполнитель обеспечивает доступность сервиса в рабочие дни.", - "Стороны сохраняют в тайне сведения, полученные друг о друге.", - "Применяется австрийское право, споры рассматривает суд Вены.", - "Исполнитель хранит резервную копию данных заказчика тридцать дней.", - "Обращения в поддержку рассматриваются в течение одного рабочего дня.", - "Заказчик назначает одного сотрудника, который вправе утверждать изменения.", - "Цены фиксируются на первый год и пересматриваются каждую осень.", - "Ни одна из сторон не вправе передать договор третьему лицу без согласия.", - "В приложении указано, какое программное обеспечение входит в договор и с какой версии.", - "Настоящий договор заменяет все прежние договорённости сторон."]], - "invoice": ["Счёт 2026-014", "Выставлен 12 июня 2026 г.", "Оплата в течение 30 дней", "Плательщик", "Промежуточный итог", "НДС 20%", "К оплате", "Благодарим за сотрудничество.", "Кол-во", "Цена за ед."], - "contacts": [["ФИО", "Отдел", "Почта", "Телефон"], - ["Дизайн", "Поддержка", "Продажи", "Разработка"]], - }, - "tr": { - "contract": ["Hizmet sözleşmesi", - "Bu sözleşme aşağıda belirtilen iki taraf arasında yapılmıştır.", - ["Tedarikçi, ekte tanımlanan yazılımı bir yıl boyunca sağlar.", - "Ödeme, her faturadan sonra otuz gün içinde yapılır.", - "Taraflardan biri sözleşmeyi üç ay önceden bildirerek sonlandırabilir.", - "Değişiklikler yalnızca yazılı olarak geçerlidir.", - "Tedarikçi hizmeti iş günlerinde erişilebilir tutar.", - "Taraflar birbirleri hakkında öğrendiklerini gizli tutar.", - "Avusturya hukuku uygulanır ve yetkili mahkeme Viyana'dır.", - "Tedarikçi, müşterinin verilerinin yedeğini otuz gün saklar.", - "Destek talepleri bir iş günü içinde yanıtlanır.", - "Müşteri, değişiklikleri onaylayabilecek bir kişi belirler.", - "Fiyatlar ilk yıl sabittir ve her sonbahar gözden geçirilir.", - "Hiçbir taraf sözleşmeyi onay almadan üçüncü kişiye devredemez.", - "Ek, kapsanan yazılımı ve geçerli olduğu sürümü listeler.", - "Bu sözleşme, taraflar arasındaki önceki tüm düzenlemelerin yerine geçer."]], - "invoice": ["Fatura 2026-014", "12 Haziran 2026 tarihli", "30 gün içinde ödenir", "Alıcı", "Ara toplam", "KDV %20", "Ödenecek tutar", "İş birliğiniz için teşekkürler.", "Adet", "Birim fiyat"], - "contacts": [["Ad Soyad", "Ekip", "E-posta", "Telefon"], - ["Tasarım", "Destek", "Satış", "Geliştirme"]], - }, -} - -# Names are names in every language, so these are not translated. -PEOPLE = ["A. Bauer", "M. Rossi", "J. Novak", "L. Dubois", "S. Meyer", "K. Larsen"] - - -# Minimal OOXML packages for screenshot samples. - -OOXML_RELS = """ - - - -""" - -WORD_MAIN = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" - -# Appendix row count and text size in half-points. -ANNEX_ROWS = 40 -CONTRACT_TEXT = 28 - - -def cell_rows(lines: list) -> str: - """A Word table of two columns, the first line of it the head.""" - out = [ - '' - '' - "" - '' - ] - for number, (name, value) in enumerate(lines): - marks = '' if number == 0 else "" - cells = "".join( - f'' - f'{marks}' - f'{escape(text)}' - for text, width in ((name, 6350), (value, 2720)) - ) - out.append(f"{cells}") - out.append("") - - return "".join(out) - - -def docx_parts(words: dict, others: dict) -> dict: - """The Word file is the contract, not another copy of the report.""" - title, lead, clauses = others["contract"] - - def run(text: str, *, size: int, bold: bool = False, colour: str = "") -> str: - marks = ("" if bold else "") + (f'' if colour else "") - - return ( - f"{marks}" - f'{escape(text)}' - ) - - def para(runs: str, after: int) -> str: - return f'{runs}' - - # Number each clause inline. - paragraphs = [ - para(run(title, size=72, bold=True), 640), - para(run(lead, size=CONTRACT_TEXT), 420), - ] - for number, clause in enumerate(clauses, start=1): - paragraphs.append( - para( - run(f"{number}. ", size=CONTRACT_TEXT, bold=True, colour=ACCENT[1:]) - + run(clause, size=CONTRACT_TEXT), - 300, - ) - ) - - # Use empty paragraphs because odrcore ignores w:spacing here. - body = ''.join(paragraphs) - - # Reuse localized table labels for the contract appendix. - _, rows, _ = table(words, columns=1, rows=ANNEX_ROWS) - body += cell_rows( - [[words["item"], words["total"]]] + [[line[0], str(line[-1])] for line in rows] - ) - - return { - "[Content_Types].xml": '' - '' - '' - '' - '' - '', - "_rels/.rels": OOXML_RELS.format(type=WORD_MAIN, target="word/document.xml"), - # odrcore requires word/styles.xml even when no named styles are used. - "word/_rels/document.xml.rels": OOXML_RELS.format( - type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", - target="styles.xml", - ), - "word/styles.xml": '' - '' - "" - '' - "" - '' - "" - '' - '' - "", - "word/document.xml": '' - '' - # A4 with 2 cm margins, measured in twentieths of a point. - f"{body}" - '' - '' - "", - } - - -def xlsx_parts(words: dict) -> dict: - """A workbook of its own figures, so it is not the .ods twice.""" - head, body, foot = table(words, columns=2, rows=8, scale=3) - rows_of = [head] + body + [foot] - - def cell(column: int, row: int, value) -> str: - reference = f"{chr(ord('A') + column)}{row}" - if isinstance(value, int): - return f'{value}' - - return f'{escape(value)}' - - rows = "".join( - f'' - + "".join(cell(column, index + 1, value) for column, value in enumerate(line)) - + "" - for index, line in enumerate(rows_of) - ) - - return { - "[Content_Types].xml": '' - '' - '' - '' - '' - '', - "_rels/.rels": OOXML_RELS.format(type=WORD_MAIN, target="xl/workbook.xml"), - "xl/_rels/workbook.xml.rels": OOXML_RELS.format( - type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", - target="worksheets/sheet1.xml", - ), - "xl/workbook.xml": '' - '' - f'', - "xl/worksheets/sheet1.xml": '' - '' - f"{rows}", - } - - -def pptx_parts(words: dict) -> dict: - """One slide, titled and bulleted, so a deck opens on something.""" - drawing = 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"' - presentation = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"' - - def shape(identifier: int, name: str, box: str, lines: list, size: int) -> str: - paragraphs = "".join( - f'' - f"{escape(line)}" - for line in lines - ) - - return ( - f'' - f"{box}" - '' - f"{paragraphs}" - ) - - slide = ( - f'' - "" - '' - + shape( - 2, - "Title", - '', - [words["slides"][0][0]], - 4000, - ) - + shape( - 3, - "Body", - '', - words["slides"][0][1], - 2000, - ) - + "" - ) - - return { - "[Content_Types].xml": '' - '' - '' - '' - '' - '', - "_rels/.rels": OOXML_RELS.format(type=WORD_MAIN, target="ppt/presentation.xml"), - "ppt/_rels/presentation.xml.rels": OOXML_RELS.format( - type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide", - target="slides/slide1.xml", - ), - "ppt/presentation.xml": f'' - f'' - '' - '', - "ppt/slides/slide1.xml": slide, - } - - -# Helvetica character widths in thousandths of a point. -HELVETICA = { - "regular": ( - "278 278 355 556 556 889 667 191 333 333 389 584 278 333 278 278 " - "556 556 556 556 556 556 556 556 556 556 278 278 584 584 584 556 " - "1015 667 667 722 722 667 611 778 722 278 500 667 556 833 722 778 " - "667 778 722 667 611 722 667 944 667 667 611 278 278 278 469 556 " - "333 556 556 500 556 556 278 556 556 222 222 500 222 833 556 556 " - "556 556 333 500 278 556 500 722 500 500 500 334 260 334 584" - ), - "bold": ( - "278 333 474 556 556 889 722 238 333 333 389 584 278 333 278 278 " - "556 556 556 556 556 556 556 556 556 556 333 333 584 584 584 611 " - "975 722 722 722 722 667 611 778 722 278 556 722 611 833 722 778 " - "667 778 722 667 611 722 667 944 667 667 611 333 278 333 584 556 " - "333 556 611 556 611 556 333 611 611 278 278 556 278 889 611 611 " - "611 611 389 556 333 611 556 778 556 556 500 389 280 389 584" - ), -} - -WIDTHS = { - weight: {chr(32 + index): int(value) for index, value in enumerate(table.split())} - for weight, table in HELVETICA.items() -} - - -def advance(text: str, weight: str, size: float) -> float: - """Measure Helvetica text in points, approximating accented letters with their base widths.""" - table = WIDTHS[weight] - total = 0 - for character in text: - width = table.get(character) - if width is None: - plain = unicodedata.normalize("NFD", character)[0] - width = table.get(plain, 556) - total += width - - return total * size / 1000 - - -WINANSI = set(bytes(range(32, 256)).decode("cp1252", errors="ignore")) - - -def spellable(words: dict, others: dict) -> bool: - """Check all invoice text against WinAnsi; unsupported locales use English.""" - spoken = [words["item"], words["total"], words["title"], words["closing"]] - spoken += words["periods"] + words["rows"] + others["invoice"] - - return all(character in WINANSI for line in spoken for character in line) - - -# A4 upright in points, with the same margin the ODF pages take. -PAGE = (595.0, 842.0) -MARGIN = 57.0 - -# Enough invoice rows to span two pages. -INVOICE_ROWS = 40 - - -def pdf_bytes(words: dict, others: dict) -> bytes: - """Build a paginated Helvetica invoice PDF, falling back to English for unsupported characters.""" - latin = spellable(words, others) - said = words if latin else WORDS["en"] - - def literal(text: str) -> str: - return text.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)") - - invoice = others["invoice"] if latin else OTHERS["en"]["invoice"] - number, issued, due, billed, subtotal, vat, due_label, thanks, quantity, unit = invoice - head, body, foot = table(said, columns=1, rows=INVOICE_ROWS) - - money = foot[-1] - tax = round(money * 0.2) - right = PAGE[0] - MARGIN - - pages = [[]] - - def put(text, x, y, weight="regular", size=10, align="left"): - """Place a line on the current page, optionally aligned right.""" - name = "F2" if weight == "bold" else "F1" - at = x - advance(text, weight, size) if align == "right" else x - pages[-1].append(f"BT /{name} {size:g} Tf {at:.1f} {y:.1f} Td ({literal(text)}) Tj ET") - - # the head: who it is from and when, against who it is to - y = PAGE[1] - MARGIN - 26 - put(number, MARGIN, y, "bold", 20) - put(issued, right, y, "regular", 10, "right") - put(due, right, y - 14, "regular", 10, "right") - - y -= 46 - put(billed, MARGIN, y, "bold", 11) - for line in ("Muster GmbH", "Praterstrasse 12", "1020 Wien"): - y -= 14 - put(line, MARGIN, y) - - # the table, in four columns across the width - columns = (MARGIN, MARGIN + 300, MARGIN + 390, right) - y -= 34 - put(head[0], columns[0], y, "bold", 10) - put(quantity, columns[1], y, "bold", 10, "right") - put(unit, columns[2], y, "bold", 10, "right") - put(head[-1], columns[3], y, "bold", 10, "right") - - for index, line in enumerate(body): - count = index % 4 + 1 - amount = line[-1] - y -= 15 - - # Start a new page and repeat column headers before reaching the bottom margin. - if y < MARGIN + 80: - pages.append([]) - y = PAGE[1] - MARGIN - 26 - put(head[0], columns[0], y, "bold", 10) - put(quantity, columns[1], y, "bold", 10, "right") - put(unit, columns[2], y, "bold", 10, "right") - put(head[-1], columns[3], y, "bold", 10, "right") - y -= 15 - - put(str(line[0]), columns[0], y) - put(str(count), columns[1], y, align="right") - put(f"{amount / count:.2f}", columns[2], y, align="right") - put(str(amount), columns[3], y, align="right") - - y -= 24 - for label, value, weight in ( - (subtotal, money, "regular"), (vat, tax, "regular"), (due_label, money + tax, "bold") - ): - put(label, columns[2], y, weight, 10 if weight == "regular" else 12, "right") - put(str(value), columns[3], y, weight, 10 if weight == "regular" else 12, "right") - y -= 17 - - y -= 12 - put(thanks, MARGIN, y) - - # 1 catalog, 2 the page tree, 3 and 4 the two fonts, then a page each and a - # content stream each - so a page is 4+n and the stream it points at 4+len+n. - first_page = 5 - first_stream = first_page + len(pages) - kids = " ".join(f"{first_page + n} 0 R" for n in range(len(pages))) - - objects = [ - b"<>", - f"<>".encode(), - b"<>", - b"<>", - ] - objects += [ - f"<>>>/Contents {first_stream + n} 0 R>>".encode() - for n in range(len(pages)) - ] - for drawn in pages: - stream = ("\n".join(drawn) + "\n").encode("cp1252") - objects.append( - b"<>\nstream\n" + stream + b"endstream" - ) - - out = bytearray(b"%PDF-1.4\n") - offsets = [] - for number, body in enumerate(objects, start=1): - offsets.append(len(out)) - out += f"{number} 0 obj\n".encode() + body + b"\nendobj\n" - - table_at = len(out) - out += f"xref\n0 {len(objects) + 1}\n".encode() + b"0000000000 65535 f \n" - for offset in offsets: - out += f"{offset:010d} 00000 n \n".encode() - out += f"trailer\n<>\nstartxref\n{table_at}\n%%EOF\n".encode() - - return bytes(out) - - -def csv_text(words: dict, others: dict) -> str: - """The contact list its name promises.""" - headers, roles = others["contacts"] - lines = [",".join(headers)] - for index, person in enumerate(PEOPLE): - handle = person.split(". ")[-1].lower() - lines.append( - ",".join([person, roles[index % len(roles)], f"{handle}@example.org", f"+43 1 234 56{index}0"]) - ) - - return "\n".join(lines) + "\n" - - -def txt_text(words: dict) -> str: - """The notes: the report in plain text, with the deck's points under it.""" - lines = [words["title"], "=" * len(words["title"]), "", words["lead"], ""] - for heading, paragraphs in words["sections"]: - lines += [heading, "-" * len(heading), ""] - for text in paragraphs: - lines += [text, ""] - for title, bullets in words["slides"]: - lines += [title, "-" * len(title), ""] - lines += [f"* {point}" for point in bullets] - lines.append("") - lines.append(words["closing"]) - - return "\n".join(lines) + "\n" - - -# What the app asks the bundle for. The first three are the documents the -# screenshots open; the rest sit in the folder the first screenshot is of. -DOCUMENTS = { - "text": ("odt", "application/vnd.oasis.opendocument.text", "document", report), - "sheet": ("ods", "application/vnd.oasis.opendocument.spreadsheet", "document", sheet), - "slides": ("odp", "application/vnd.oasis.opendocument.presentation", "slide", deck), -} - -PACKAGES = { - "word": ("docx", docx_parts), - "cells": ("xlsx", xlsx_parts), - "deck": ("pptx", pptx_parts), -} - -PLAIN = { - "rows": ("csv", csv_text), - "notes": ("txt", txt_text), -} - - -def package(path: Path, parts: dict) -> None: - """A zip of the given parts, reproducibly.""" - with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive: - for name, text in parts.items(): - info = zipfile.ZipInfo(name, date_time=EPOCH) - info.external_attr = 0o644 << 16 - archive.writestr(info, text, compress_type=zipfile.ZIP_DEFLATED) - - -def write(path: Path, mimetype: str, kind: str, content_xml: str) -> None: - with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as package: - def entry(name: str, text: str, stored: bool = False) -> None: - info = zipfile.ZipInfo(name, date_time=EPOCH) - info.external_attr = 0o644 << 16 - package.writestr( - info, text, compress_type=zipfile.ZIP_STORED if stored else zipfile.ZIP_DEFLATED - ) - - # first and uncompressed, or the package is only recognised by sniffing - entry("mimetype", mimetype, stored=True) - entry("META-INF/manifest.xml", MANIFEST.format(mimetype=mimetype)) - entry("styles.xml", styles(kind)) - entry("content.xml", content_xml) + raise SystemExit(f"{REQUIREMENTS.name} pins no sampledoc==") def main(argv=None) -> None: + # Only the languages the store is photographed in; locales mapped to None borrow English. + spoken = sorted({language for language in store.LOCALES.values() if language}) + parser = argparse.ArgumentParser(description="Write the documents the store screenshots open.") parser.add_argument( - "--language", action="append", choices=sorted(WORDS), - help="only this language, repeatable; default is all of them. What to reach for when a " - "change is worded in English first and the rest are to follow.") + "--language", action="append", choices=spoken, + help="only this language, repeatable; default is all of them.") args = parser.parse_args(argv) - languages = args.language or list(WORDS) - - SAMPLES.mkdir(parents=True, exist_ok=True) - - written = 0 - for language in languages: - words = WORDS[language] - for name, (extension, mimetype, kind, build) in DOCUMENTS.items(): - path = SAMPLES / f"sample-{name}-{language}.{extension}" - write(path, mimetype, kind, build(words)) - written += 1 - - others = OTHERS[language] - - for name, (extension, build) in PACKAGES.items(): - parts = build(words, others) if name == "word" else build(words) - package(SAMPLES / f"sample-{name}-{language}.{extension}", parts) - written += 1 + wanted = pinned() + try: + import sampledoc + except ImportError: + raise SystemExit( + f"sampledoc is not installed - python3 -m pip install -r scripts/{REQUIREMENTS.name}" + ) from None + + # Another version writes other documents, so the screenshots would depend on who took them. + if sampledoc.__version__ != wanted: + raise SystemExit( + f"sampledoc {sampledoc.__version__} is installed but {wanted} is pinned - " + f"python3 -m pip install -r scripts/{REQUIREMENTS.name}" + ) - for name, (extension, build) in PLAIN.items(): - text = build(words, others) if name == "rows" else build(words) - (SAMPLES / f"sample-{name}-{language}.{extension}").write_text(text, encoding="utf-8") - written += 1 + missing = sorted(set(spoken) - set(sampledoc.languages())) + if missing: + raise SystemExit(f"store_screenshots.py photographs languages sampledoc lacks: {missing}") - (SAMPLES / f"sample-paper-{language}.pdf").write_bytes(pdf_bytes(words, others)) - written += 1 + written = sampledoc.generate(SAMPLES, languages=args.language or spoken) - details = { - language: { - "files": FILE_NAMES[language] - | { - key: FILLER_NAMES.get(language, {}).get(key, FILLER_NAMES["en"][key]) - for key in FILLERS - }, - "search": query(words), - } - for language, words in WORDS.items() - } + details = sampledoc.manifest(store.LOCALES) + details["languages"] = {language: details["languages"][language] for language in spoken} (SAMPLES / "screenshot-names.json").write_text( json.dumps(details, ensure_ascii=False, indent=1, sort_keys=True) + "\n", encoding="utf-8" ) - print(f"wrote {written} documents in {len(languages)} languages to {SAMPLES}") + print(f"wrote {len(written)} documents in {len(args.language or spoken)} languages to {SAMPLES}") if __name__ == "__main__": diff --git a/scripts/requirements.txt b/scripts/requirements.txt index 3db1031..e1b01b1 100644 --- a/scripts/requirements.txt +++ b/scripts/requirements.txt @@ -1,4 +1,6 @@ -# The store screenshots are framed by storeframe (https://pypi.org/project/storeframe/). -# Pinned, so a release run frames the same pictures as the last one. +# The store screenshots are framed by storeframe (https://pypi.org/project/storeframe/), +# and the samples in them are written by sampledoc (https://pypi.org/project/sampledoc/). +# Pinned, so a release run frames and photographs the same pictures as the last one. # python3 -m pip install -r scripts/requirements.txt storeframe==0.1.0 +sampledoc==0.1.0