thibaud frere commited on
Commit ·
b2ac38d
1
Parent(s): e329457
update
Browse filesFiles changed (13)
- README.md+1-1
- app/.astro/astro/content.d.ts+169
- app/scripts/export-pdf.mjs+2-16
- app/src/components/Header.astro+4-3
- app/src/content/article.mdx+21-19
- app/src/pages/index.astro+4-7
- app/src/styles/_base.scss+1-1
- app/src/styles/_layout.scss+2-2
- app/src/styles/components/_code.scss+1-1
- app/src/styles/components/_footer.scss+1-1
- fragments/plotly/banner.py+26-26
- fragments/plotly/line.py+2-2
- fragments/plotly/pyproject.toml+1-1
12345---title: 'The science article template'emoji: 📝colorFrom: bluecolorTo: indigo12345---title: 'Research article template'emoji: 📝colorFrom: bluecolorTo: indigo
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169declare module 'astro:content' {interface Render {'.mdx': Promise<{Content: import('astro').MarkdownInstance<{}>['Content'];headings: import('astro').MarkdownHeading[];remarkPluginFrontmatter: Record<string, any>;components: import('astro').MDXInstance<{}>['components'];}>;}}declare module 'astro:content' {interface RenderResult {Content: import('astro/runtime/server/index.js').AstroComponentFactory;headings: import('astro').MarkdownHeading[];remarkPluginFrontmatter: Record<string, any>;}interface Render {'.md': Promise<RenderResult>;}export interface RenderedContent {html: string;metadata?: {imagePaths: Array<string>;[key: string]: unknown;};}}declare module 'astro:content' {type Flatten<T> = T extends { [K: string]: infer U } ? U : never;export type CollectionKey = keyof AnyEntryMap;export type CollectionEntry<C extends CollectionKey> = Flatten<AnyEntryMap[C]>;export type ContentCollectionKey = keyof ContentEntryMap;export type DataCollectionKey = keyof DataEntryMap;type AllValuesOf<T> = T extends any ? T[keyof T] : never;type ValidContentEntrySlug<C extends keyof ContentEntryMap> = AllValuesOf<ContentEntryMap[C]>['slug'];/** @deprecated Use `getEntry` instead. */export function getEntryBySlug<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(collection: C,// Note that this has to accept a regular string too, for SSRentrySlug: E,): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;/** @deprecated Use `getEntry` instead. */export function getDataEntryById<C extends keyof DataEntryMap, E extends keyof DataEntryMap[C]>(collection: C,entryId: E,): Promise<CollectionEntry<C>>;export function getCollection<C extends keyof AnyEntryMap, E extends CollectionEntry<C>>(collection: C,filter?: (entry: CollectionEntry<C>) => entry is E,): Promise<E[]>;export function getCollection<C extends keyof AnyEntryMap>(collection: C,filter?: (entry: CollectionEntry<C>) => unknown,): Promise<CollectionEntry<C>[]>;export function getEntry<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(entry: {collection: C;slug: E;}): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof DataEntryMap,E extends keyof DataEntryMap[C] | (string & {}),>(entry: {collection: C;id: E;}): E extends keyof DataEntryMap[C]? Promise<DataEntryMap[C][E]>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof ContentEntryMap,E extends ValidContentEntrySlug<C> | (string & {}),>(collection: C,slug: E,): E extends ValidContentEntrySlug<C>? Promise<CollectionEntry<C>>: Promise<CollectionEntry<C> | undefined>;export function getEntry<C extends keyof DataEntryMap,E extends keyof DataEntryMap[C] | (string & {}),>(collection: C,id: E,): E extends keyof DataEntryMap[C]? Promise<DataEntryMap[C][E]>: Promise<CollectionEntry<C> | undefined>;/** Resolve an array of entry references from the same collection */export function getEntries<C extends keyof ContentEntryMap>(entries: {collection: C;slug: ValidContentEntrySlug<C>;}[],): Promise<CollectionEntry<C>[]>;export function getEntries<C extends keyof DataEntryMap>(entries: {collection: C;id: keyof DataEntryMap[C];}[],): Promise<CollectionEntry<C>[]>;export function render<C extends keyof AnyEntryMap>(entry: AnyEntryMap[C][string],): Promise<RenderResult>;export function reference<C extends keyof AnyEntryMap>(collection: C,): import('astro/zod').ZodEffects<import('astro/zod').ZodString,C extends keyof ContentEntryMap? {collection: C;slug: ValidContentEntrySlug<C>;}: {collection: C;id: keyof DataEntryMap[C];}>;// Allow generic `string` to avoid excessive type errors in the config// if `dev` is not running to update as you edit.// Invalid collection names will be caught at build time.export function reference<C extends string>(collection: C,): import('astro/zod').ZodEffects<import('astro/zod').ZodString, never>;type ReturnTypeOrOriginal<T> = T extends (...args: any[]) => infer R ? R : T;type InferEntrySchema<C extends keyof AnyEntryMap> = import('astro/zod').infer<ReturnTypeOrOriginal<Required<ContentConfig['collections'][C]>['schema']>>;type ContentEntryMap = {};type DataEntryMap = {"fragments": Record<string, {id: string;collection: "fragments";data: any;}>;};type AnyEntryMap = ContentEntryMap & DataEntryMap;export type ContentConfig = never;}
1 unmodified line2345678171 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042051 unmodified lineimport { spawn } from 'node:child_process';import { setTimeout as delay } from 'node:timers/promises';import { chromium } from 'playwright';import { resolve, basename } from 'node:path';import { promises as fs } from 'node:fs';import process from 'node:process';171 unmodified lines});console.log(`✅ PDF generated: ${outPath}`);// Compatibility copy into dist/article.pdf (for servers that only serve dist)const distCompatPath = resolve(cwd, 'dist', 'article.pdf');try {if (basename(outPath) !== 'article.pdf') {await fs.copyFile(outPath, distCompatPath);console.log(`✅ PDF copied (dist compat): ${distCompatPath}`);}} catch (e) {console.warn('Unable to copy PDF to dist/article.pdf:', e?.message || e);}// Also copy into public under 2 names: slug.pdf and article.pdf (compat)const publicSlugPath = resolve(cwd, 'public', `${outFileBase}.pdf`);const publicCompatPath = resolve(cwd, 'public', 'article.pdf');try {await fs.mkdir(resolve(cwd, 'public'), { recursive: true });await fs.copyFile(outPath, publicSlugPath);await fs.copyFile(outPath, publicCompatPath);console.log(`✅ PDF copied to: ${publicSlugPath}`);console.log(`✅ PDF copied (compat): ${publicCompatPath}`);} catch (e) {console.warn('Unable to copy PDF to public/:', e?.message || e);}1 unmodified line2345678171 unmodified lines1801811821831841851861871881891901911 unmodified lineimport { spawn } from 'node:child_process';import { setTimeout as delay } from 'node:timers/promises';import { chromium } from 'playwright';import { resolve } from 'node:path';import { promises as fs } from 'node:fs';import process from 'node:process';171 unmodified lines});console.log(`✅ PDF generated: ${outPath}`);// Copy into public only under the slugified nameconst publicSlugPath = resolve(cwd, 'public', `${outFileBase}.pdf`);try {await fs.mkdir(resolve(cwd, 'public'), { recursive: true });await fs.copyFile(outPath, publicSlugPath);console.log(`✅ PDF copied to: ${publicSlugPath}`);} catch (e) {console.warn('Unable to copy PDF to public/:', e?.message || e);}
12341 unmodified line678910111213141516---interface Props {title: string;description?: string;1 unmodified lineconst { title, description } = Astro.props as Props;---<section class="hero"><h1 class="hero-title">{title}</h1><div class="hero-banner"><slot name="banner" />{description && <p class="hero-desc">{description}</p>}</div></section>1234561 unmodified line891011121314151617---import HtmlFragment from "./HtmlFragment.astro";interface Props {title: string;description?: string;1 unmodified lineconst { title, description } = Astro.props as Props;---<section class="hero"><h1 class="hero-title" set:html={title}></h1><div class="hero-banner"><HtmlFragment src="banner.html" />{description && <p class="hero-desc">{description}</p>}</div></section>
12345633 unmodified lines4041424344454647 unmodified lines9495969798991002 unmodified lines10310410510610710810911011111211311411511611721 unmodified lines13914014114214314414531 unmodified lines17717817918018118218325 unmodified lines20921021121221321421527 unmodified lines24324424524624724824925025125225311 unmodified lines26526626726826927027127227374 unmodified lines3483493503513523533547 unmodified lines36236336436536636736838 unmodified lines4074084094104114124134144154164174184194201 unmodified line422423424425426---title: "From Idea to Interactive:\n A Modern Template for Scientific Writing"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"33 unmodified linesThis template is inspired by [**Distill**](https://distill.pub); we aim to preserve the best of it while modernizing the stack. Their work is highly inspiring.## Features<div className="tag-list"><span className="tag">Markdown based</span>47 unmodified lines### Large files (Git LFS)Track binaries (e.g., `.png`, `.wav`) with Git LFS to keep the repository lean. This project is preconfigured to store such files via LFS.## Writing Your Content2 unmodified linesYour article lives in two places:- `app/src/content/` — where you can find the article.mdx and bibliography.bib.- `app/src/assets/` — images, audio, and other static assets. (handled by git lfs)The initial skeleton of an article looks like this:```mdx{/* HEADER */}---title: "The science template:\nCraft Beautiful Blogs"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"21 unmodified lines**Available blocs**:<div className="tag-list"><a className="tag" href="#math">Math</a>31 unmodified lines### ImagesResponsive images automatically generate an optimized `srcset` and `sizes` so the browser downloads the most appropriate file for the current viewport and DPR. You can also request multiple output formats (e.g., **AVIF**, **WebP**, fallback **PNG/JPEG**) and control lazy loading/decoding for better performance.**Optional:** Zoomable (Medium-like lightbox): add `data-zoomable` to opt-in. Only images with this attribute will open full-screen on click.25 unmodified lines<Image src={myImage} data-zoomable alt="Example with caption and credit" loading="lazy" /><figcaption>Optimized image with a descriptive caption.<span className="image-credit">Crédit: Photo by <a href="https://example.com">Author</a></span></figcaption></figure>```27 unmodified linesHere are a few variations using the same bibliography:1) In-text citation with brackets: [@example2023].2) Narrative citation: As shown by @vaswani2017attention, transformers enable efficient sequence modeling.3) Multiple citations and a footnote together: see [@vaswani2017attention; @example2023] for related work. Also note this footnote[^f1].[^f1]: Footnote attached to the sentence above.11 unmodified lines### Asides<Aside>This paragraph presents a key idea concisely.<Fragment slot="aside">Side note for brief context or a definition.</Fragment></Aside>74 unmodified lines#### Html FragmentsThe main purpose of the ```HtmlFragment``` component is to embed a plotly or d3 chart in your article. Libraries are already imported in the template.<div className="plot-card"><HtmlFragment src="line.html" />7 unmodified lines#### IframesYou can embed external content in your article using **iframes**. For example, TrackIO—a lightweight dashboard to monitor machine learning experiments—can be used this way. The example below opens a demo project and displays a couple of metrics. You can customize the query parameters (`project`, `metrics`, `sidebar`, etc.) to fit your needs.<iframe className="plot-card" src="https://trackio-documentation.hf.space/?project=fake-training-750735&metrics=train_loss,train_accuracy&sidebar=hidden&lang=en" width="100%" height="600" frameborder="0"></iframe>38 unmodified lines### Use the right chartPicking the right visualization depends on your goal (compare values, show distribution, part-to-whole, trends, relationships, etc.). The Visual Vocabulary poster below provides a concise mapping from analytical task to chart types.<figure><a href="https://ft-interactive.github.io/visual-vocabulary/" target="_blank" rel="noopener noreferrer"><Image src={visualPoster} alt="Visual Vocabulary: choosing the right chart by task" /></a><figcaption>Visual Vocabulary: a handy reference to select chart types by purpose (comparison, distribution, part-to-whole, correlation, and more).— <a href="https://ft-interactive.github.io/visual-vocabulary/" target="_blank" rel="noopener noreferrer">Website</a></figcaption></figure>1 unmodified line## ConclusionsThis template provides a practical baseline for writing and sharing technical articles with math, citations, and interactive figures. Start simple, iterate on structure and style, and keep content maintainable for future readers and collaborators.123456733 unmodified lines4142434445464747 unmodified lines95969798991001012 unmodified lines10410510610710810911011111211311411511611711811921 unmodified lines14114214314414514614731 unmodified lines17918018118218318418525 unmodified lines21121221321421521621727 unmodified lines24524624724824925025125225325425511 unmodified lines26726826927027127227327427574 unmodified lines3503513523533543553567 unmodified lines36436536636736836937038 unmodified lines4094104114124134144154164174184194204214221 unmodified line424425426427428---title: "From Idea to Interactive:\n A Modern Template for Scientific Writing"subtitle: "It's nice to have a cute interactive banner"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"33 unmodified linesThis template is inspired by [**Distill**](https://distill.pub); we aim to preserve the best of it while modernizing the stack. Their work is highly inspiring.#### Features<div className="tag-list"><span className="tag">Markdown based</span>47 unmodified lines### Large files (Git LFS)**Track binaries** (e.g., `.png`, `.wav`) with **Git LFS** to keep the repository lean. This project is preconfigured to store such files via **LFS**.## Writing Your Content2 unmodified linesYour article lives in two places:- `app/src/content/` — where you can find the article.mdx, bibliography.bib and html fragments.- `app/src/assets/` — images, audio, and other static assets. (handled by git lfs)The **initial skeleton** of an article looks like this:```mdx{/* HEADER */}---title: "This is the main title"subtitle: "This will be displayed just below the banner"description: "A modern, MDX-first research article template with math, citations, and interactive figures."authors:- "John Doe"21 unmodified lines**Available blocks**:<div className="tag-list"><a className="tag" href="#math">Math</a>31 unmodified lines### Images**Responsive images** automatically generate an optimized `srcset` and `sizes` so the browser downloads the most appropriate file for the current viewport and DPR. You can also request multiple output formats (e.g., **AVIF**, **WebP**, fallback **PNG/JPEG**) and control **lazy loading/decoding** for better **performance**.**Optional:** Zoomable (Medium-like lightbox): add `data-zoomable` to opt-in. Only images with this attribute will open full-screen on click.25 unmodified lines<Image src={myImage} data-zoomable alt="Example with caption and credit" loading="lazy" /><figcaption>Optimized image with a descriptive caption.<span className="image-credit">Credit: Photo by <a href="https://example.com">Author</a></span></figcaption></figure>```27 unmodified linesHere are a few variations using the same bibliography:1) **In-text citation** with brackets: [@example2023].2) **Narrative citation**: As shown by @vaswani2017attention, transformers enable efficient sequence modeling.3) **Multiple citations** and a **footnote** together: see [@vaswani2017attention; @example2023] for related work. Also note this footnote[^f1].[^f1]: Footnote attached to the sentence above.11 unmodified lines### Asides<Aside>This paragraph presents a **key idea** concisely.<Fragment slot="aside">**Side note** for brief context or a definition.</Fragment></Aside>74 unmodified lines#### Html FragmentsThe main purpose of the ```HtmlFragment``` component is to embed a **Plotly** or **D3.js** chart in your article. Libraries are already imported in the template.<div className="plot-card"><HtmlFragment src="line.html" />7 unmodified lines#### IframesYou can embed external content in your article using **iframes**. For example, **TrackIO**—a lightweight dashboard to monitor machine learning experiments—can be used this way. The example below opens a demo project and displays a couple of metrics. You can customize the **query parameters** (`project`, `metrics`, `sidebar`, etc.) to fit your needs.<iframe className="plot-card" src="https://trackio-documentation.hf.space/?project=fake-training-750735&metrics=train_loss,train_accuracy&sidebar=hidden&lang=en" width="100%" height="600" frameborder="0"></iframe>38 unmodified lines### Use the right chartPicking the right visualization depends on your goal (compare values, show distribution, part-to-whole, trends, relationships, etc.). The Visual Vocabulary poster below provides a concise mapping from **analytical task** to **chart types**.<figure><a href={visualPoster.src} target="_blank" rel="noopener noreferrer"><Image src={visualPoster} alt="Visual Vocabulary: choosing the right chart by task" /></a><figcaption>A handy reference to select chart types by purpose. Click to enlarge.— <a href="https://ft-interactive.github.io/visual-vocabulary/" target="_blank" rel="noopener noreferrer">Website</a></figcaption></figure>1 unmodified line## ConclusionsThis template provides a **practical baseline** for writing and sharing technical articles with **math**, **citations**, and **interactive figures**. **Start simple**, **iterate** on structure and style, and keep content **maintainable** for future readers and collaborators.
2 unmodified lines3456784 unmodified lines13141516171852 unmodified lines717273747576777879808182832 unmodified linesimport Meta from '../components/Meta.astro';import HtmlFragment from '../components/HtmlFragment.astro';import Footer from '../components/Footer.astro';import ThemeToggle from '../components/ThemeToggle.astro';import SeoHead from '../components/SeoHead.astro';import ogDefault from '../assets/images/visual-vocabulary-poster.png';4 unmodified linesconst docTitleHtml = (articleFM?.title ?? 'Untitled article').replace(/\\n/g, '<br/>').replace(/\n/g, '<br/>');const description = articleFM?.description ?? '';const authors = articleFM?.authors ?? [];const published = articleFM?.published ?? undefined;52 unmodified lines</head><body><ThemeToggle /><section class="hero"><h1 class="hero-title" set:html={docTitleHtml}></h1><div class="hero-banner"><HtmlFragment src="banner.html" /><p class="hero-desc">It's nice to have a cute interactive banner!</p></div></section><section class="article-header"><Meta title={docTitle} authors={articleFM?.authors} affiliation={articleFM?.affiliation} published={articleFM?.published} />2 unmodified lines34567894 unmodified lines1415161718192052 unmodified lines73747576777879802 unmodified linesimport Meta from '../components/Meta.astro';import HtmlFragment from '../components/HtmlFragment.astro';import Footer from '../components/Footer.astro';import Header from '../components/Header.astro';import ThemeToggle from '../components/ThemeToggle.astro';import SeoHead from '../components/SeoHead.astro';import ogDefault from '../assets/images/visual-vocabulary-poster.png';4 unmodified linesconst docTitleHtml = (articleFM?.title ?? 'Untitled article').replace(/\\n/g, '<br/>').replace(/\n/g, '<br/>');const subtitle = articleFM?.subtitle ?? '';const description = articleFM?.description ?? '';const authors = articleFM?.authors ?? [];const published = articleFM?.published ?? undefined;52 unmodified lines</head><body><ThemeToggle /><Header title={docTitleHtml} description={subtitle}></Header><section class="article-header"><Meta title={docTitle} authors={articleFM?.authors} affiliation={articleFM?.affiliation} published={articleFM?.published} />
185 unmodified lines186187188189190191192185 unmodified lines.image-credit a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }// ============================================================================// Buttons (minimal, épuré)// ============================================================================.meta .meta-container-cell button {appearance: none;185 unmodified lines186187188189190191192185 unmodified lines.image-credit a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }// ============================================================================// Buttons (minimal, clean)// ============================================================================.meta .meta-container-cell button {appearance: none;
21 unmodified lines22232425262728293021 unmodified lines// Mobile TOC accordion.toc-mobile { display: none; margin: 8px 0 16px; }.toc-mobile > summary { cursor: pointer; list-style: none; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--surface-bg); color: var(--text-color); font-weight: 600; }.toc-mobile[open] > summary { border-bottom-left-radius: 0; border-bottom-right-radius: 0; }.toc-mobile nav { border-left: none; padding: 10px 12px; font-size: 14px; border: 1px solid var(--border-color); border-top: none; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; background: var(--surface-bg); }.toc-mobile nav ul { margin: 0 0 6px; padding-left: 1em; }.toc-mobile nav li { list-style: none; margin: .25em 0; }.toc-mobile nav a { color: var(--text-color); text-decoration: none; border-bottom: none; }21 unmodified lines22232425262728293021 unmodified lines// Mobile TOC accordion.toc-mobile { display: none; margin: 8px 0 16px; }.toc-mobile > summary { cursor: pointer; list-style: none; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-color); font-weight: 600; }.toc-mobile[open] > summary { border-bottom-left-radius: 0; border-bottom-right-radius: 0; }.toc-mobile nav { border-left: none; padding: 10px 12px; font-size: 14px; border: 1px solid var(--border-color); border-top: none; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; }.toc-mobile nav ul { margin: 0 0 6px; padding-left: 1em; }.toc-mobile nav li { list-style: none; margin: .25em 0; }.toc-mobile nav a { color: var(--text-color); text-decoration: none; border-bottom: none; }
8 unmodified lines91011121314158 unmodified linessection.content-grid pre code { display: inline-block; min-width: 100%; }/* Wrap long lines on mobile to avoid overflow (URLs, etc.) */@media (max-width: 700px) {.astro-code,section.content-grid pre { white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; }section.content-grid pre code { white-space: pre-wrap; display: block; min-width: 0; }8 unmodified lines91011121314158 unmodified linessection.content-grid pre code { display: inline-block; min-width: 100%; }/* Wrap long lines on mobile to avoid overflow (URLs, etc.) */@media (max-width: 1100px) {.astro-code,section.content-grid pre { white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; }section.content-grid pre code { white-space: pre-wrap; display: block; min-width: 0; }
1234567.distill-footer { contain: layout style; font-size: 0.8em; line-height: 1.7em; margin-top: 60px; margin-bottom: 0; border-top: 1px solid rgba(0, 0, 0, 0.1); color: rgba(0, 0, 0, 0.5); }.footer-inner { max-width: 1280px; margin: 0 auto; padding: 60px 16px 48px; display: grid; grid-template-columns: 220px minmax(0, 680px) 260px; gap: 32px; align-items: start; }// Utiliser la grille parent (3 colonnes comme .content-grid).citation-block,.references-block { display: contents; }.citation-block > h3,1234567.distill-footer { contain: layout style; font-size: 0.8em; line-height: 1.7em; margin-top: 60px; margin-bottom: 0; border-top: 1px solid rgba(0, 0, 0, 0.1); color: rgba(0, 0, 0, 0.5); }.footer-inner { max-width: 1280px; margin: 0 auto; padding: 60px 16px 48px; display: grid; grid-template-columns: 220px minmax(0, 680px) 260px; gap: 32px; align-items: start; }// Use the parent grid (3 columns like .content-grid).citation-block,.references-block { display: contents; }.citation-block > h3,
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636 unmodified lines707172737475767778791 unmodified lineimport numpy as npimport pandas as pd# Paramètres de la scène (mêmes ranges que l'intégration Astro)cx, cy = 1.5, 0.5 # centrea, b = 1.3, 0.45 # étendue max en x/y (ellipse pour l'anisotropie)# Paramètres de la galaxie en spiralenum_points = 3000 # plus de dotsnum_arms = 3 # nombre de bras spirauxnum_turns = 2.1 # nombre de tours par brasangle_jitter = 0.12 # écart angulaire pour évaser les braspos_noise = 0.015 # bruit de position global# Génération des points sur des bras spiraux (spirale d'Archimède)t = np.random.rand(num_points) * (2 * np.pi * num_turns) # progression le long du brasarm_indices = np.random.randint(0, num_arms, size=num_points)arm_offsets = arm_indices * (2 * np.pi / num_arms)theta = t + arm_offsets + np.random.randn(num_points) * angle_jitter# Rayon normalisé (0->centre, 1->bord). Puissance <1 pour densifier le centrer_norm = (t / (2 * np.pi * num_turns)) ** 0.9# Bruit radial/lateral qui augmente légèrement avec le rayonnoise_x = pos_noise * (0.8 + 0.6 * r_norm) * np.random.randn(num_points)noise_y = pos_noise * (0.8 + 0.6 * r_norm) * np.random.randn(num_points)# Projection elliptiquex_spiral = cx + a * r_norm * np.cos(theta) + noise_xy_spiral = cy + b * r_norm * np.sin(theta) + noise_y# Bulbe central (points supplémentaires très proches du centre)bulge_points = int(0.18 * num_points)phi_b = 2 * np.pi * np.random.rand(bulge_points)r_b = (np.random.rand(bulge_points) ** 2.2) * 0.22 # bulbe compactnoise_x_b = (pos_noise * 0.6) * np.random.randn(bulge_points)noise_y_b = (pos_noise * 0.6) * np.random.randn(bulge_points)x_bulge = cx + a * r_b * np.cos(phi_b) + noise_x_by_bulge = cy + b * r_b * np.sin(phi_b) + noise_y_b# Concaténationx = np.concatenate([x_spiral, x_bulge])y = np.concatenate([y_spiral, y_bulge])# Intensité centrale (pour tailles/couleurs). 1 au centre, ~0 au bordz_spiral = 1 - r_normz_bulge = 1 - (r_b / max(r_b.max(), 1e-6)) # bulbe très lumineuxz_raw = np.concatenate([z_spiral, z_bulge])# Tailles: conserver l'échelle 5..10 pour cohérencesizes = (z_raw + 1) * 5# Suppression du filtre intermédiaire: on garde tous les points posés, on filtrera à la toute findf = pd.DataFrame({"x": x,"y": y,"z": sizes, # réutilisé pour size+color comme avant})def get_label(z):6 unmodified lineselse:return "biiig dot"# Labels basés sur l'intensité centraledf["label"] = pd.Series(z_raw).apply(get_label)# Ordonnancement pour le rendu: petits d'abord, gros ensuite (au-dessus)df = df.sort_values(by="z", ascending=True).reset_index(drop=True)fig = go.Figure()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636 unmodified lines707172737475767778791 unmodified lineimport numpy as npimport pandas as pd# Scene parameters (same ranges as the Astro integration)cx, cy = 1.5, 0.5 # centera, b = 1.3, 0.45 # max extent in x/y (ellipse for anisotropy)# Spiral galaxy parametersnum_points = 3000 # more dotsnum_arms = 3 # number of spiral armsnum_turns = 2.1 # number of turns per armangle_jitter = 0.12 # angular jitter to fan out the armspos_noise = 0.015 # global position noise# Generate points along spiral arms (Archimedean spiral)t = np.random.rand(num_points) * (2 * np.pi * num_turns) # progression along the armarm_indices = np.random.randint(0, num_arms, size=num_points)arm_offsets = arm_indices * (2 * np.pi / num_arms)theta = t + arm_offsets + np.random.randn(num_points) * angle_jitter# Normalized radius (0->center, 1->edge). Power <1 to densify the corer_norm = (t / (2 * np.pi * num_turns)) ** 0.9# Radial/lateral noise that slightly increases with radiusnoise_x = pos_noise * (0.8 + 0.6 * r_norm) * np.random.randn(num_points)noise_y = pos_noise * (0.8 + 0.6 * r_norm) * np.random.randn(num_points)# Elliptic projectionx_spiral = cx + a * r_norm * np.cos(theta) + noise_xy_spiral = cy + b * r_norm * np.sin(theta) + noise_y# Central bulge (additional points very close to the core)bulge_points = int(0.18 * num_points)phi_b = 2 * np.pi * np.random.rand(bulge_points)r_b = (np.random.rand(bulge_points) ** 2.2) * 0.22 # compact bulgenoise_x_b = (pos_noise * 0.6) * np.random.randn(bulge_points)noise_y_b = (pos_noise * 0.6) * np.random.randn(bulge_points)x_bulge = cx + a * r_b * np.cos(phi_b) + noise_x_by_bulge = cy + b * r_b * np.sin(phi_b) + noise_y_b# Concatenationx = np.concatenate([x_spiral, x_bulge])y = np.concatenate([y_spiral, y_bulge])# Central intensity (for sizes/colors). 1 at center, ~0 at edgez_spiral = 1 - r_normz_bulge = 1 - (r_b / max(r_b.max(), 1e-6)) # very bright bulgez_raw = np.concatenate([z_spiral, z_bulge])# Sizes: keep the 5..10 scale for consistencysizes = (z_raw + 1) * 5# Remove intermediate filtering: keep all placed points, filter at the very enddf = pd.DataFrame({"x": x,"y": y,"z": sizes, # reused for size+color as before})def get_label(z):6 unmodified lineselse:return "biiig dot"# Labels based on central intensitydf["label"] = pd.Series(z_raw).apply(get_label)# Rendering order: small points first, big ones after (on top)df = df.sort_values(by="z", ascending=True).reset_index(drop=True)fig = go.Figure()
119 unmodified lines120121122123124125126127128129130119 unmodified lines),)# Écrit le fragment de manière robuste à côté de ce fichier, dans src/fragments/line.htmloutput_path = os.path.join(os.path.dirname(__file__), "fragments", "line.html")os.makedirs(os.path.dirname(output_path), exist_ok=True)# Injecte un petit script post-rendu pour arrondir les coins de la boîte de hoverpost_script = """(function(){function attach(gd){119 unmodified lines120121122123124125126127128129130119 unmodified lines),)# Write the fragment next to this file into src/fragments/line.html (robust path)output_path = os.path.join(os.path.dirname(__file__), "fragments", "line.html")os.makedirs(os.path.dirname(output_path), exist_ok=True)# Inject a small post-render script to round the hover box cornerspost_script = """(function(){function attach(gd){
1234567[tool.poetry]name = "blogpost-fine-tasks-python"version = "0.1.0"description = "Scripts de génération de fragments Plotly et conversions HTML/Markdown pour le blogpost."package-mode = false[tool.poetry.dependencies]1234567[tool.poetry]name = "blogpost-fine-tasks-python"version = "0.1.0"description = "Plotly fragment generation scripts and HTML/Markdown conversions for the blogpost."package-mode = false[tool.poetry.dependencies]
README.md+1-1
app/.astro/astro/content.d.ts+169
app/scripts/export-pdf.mjs+2-16
app/src/components/Header.astro+4-3
app/src/content/article.mdx+21-19
app/src/pages/index.astro+4-7
app/src/styles/_base.scss+1-1
app/src/styles/_layout.scss+2-2
app/src/styles/components/_code.scss+1-1
app/src/styles/components/_footer.scss+1-1
fragments/plotly/banner.py+26-26
fragments/plotly/line.py+2-2
fragments/plotly/pyproject.toml+1-1