thibaud frere commited on
Commit ·
ad5db07
1
Parent(s): 8593dc4
add latex exporter and latex-converter projects
Browse filesFiles changed (16)
- .gitignore+2
- COLLABORATION.mdDeleted-130
- README.md+1-41
- app/.astro/astro/content.d.ts+24-36
- app/package.json
- app/scripts/export-latex.mjs+40-40
- app/scripts/latex-converter/README.mdAdded+107
- app/scripts/latex-converter/bibliography-cleaner.mjsAdded+123
- app/scripts/latex-converter/config.mjsAdded+59
- app/scripts/latex-converter/converter.mjsAdded+456
- app/scripts/latex-converter/image-transformer.mjsAdded+179
- app/scripts/latex-converter/index.mjsAdded+75
- app/scripts/latex-converter/preprocessor.mjsAdded+115
- app/scripts/latex-converter/robust-preprocessor.mjsAdded+399
- app/src/content/article.mdx+1-2
- scripts/setup-collaboration.shDeleted-44
18 unmodified lines19202122232418 unmodified lines*.env*.cache# PDF exportapp/public/*.pdfapp/public/*.png18 unmodified lines192021222324252618 unmodified lines*.env*.cacheapp/scripts/latex-converter/input-example/# PDF exportapp/public/*.pdfapp/public/*.png
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# 👥 Guide de Collaboration - Research Article Template
## 🚀 Démarrage rapide
### **Pour l'organisateur (host)**
1. **Créer un Codespace** : ```bash # Via GitHub web : bouton "Code" → "Codespaces" → "Create codespace" # Ou via CLI : gh codespace create --repo YOUR_USERNAME/research-article-template ```
2. **Lancer l'environnement collaboratif** : ```bash ./scripts/setup-collaboration.sh ```
3. **Démarrer Live Share** : - `Ctrl+Shift+P` → `Live Share: Start Collaborative Session` - Copier le lien généré et l'envoyer aux collaborateurs
### **Pour les collaborateurs (guests)**
1. **Rejoindre via le lien Live Share** : - Cliquer sur le lien reçu - Se connecter avec GitHub/Microsoft - VS Code s'ouvre automatiquement dans le navigateur
2. **Ou via VS Code local** : - Installer l'extension "Live Share" - `Ctrl+Shift+P` → `Live Share: Join Collaborative Session` - Coller le lien
## 🎯 Workflow collaboratif
### **Organisation des tâches**```📝 Rédaction:├── Alice → chapters/introduction.mdx├── Bob → chapters/methodology.mdx └── Carol → chapters/results.mdx
🎨 Visualisations:├── David → embeds/d3-charts.html└── Eve → src/content/assets/data/
📚 Références:└── Frank → bibliography.bib```
### **Bonnes pratiques**
✅ **Coordination** :- Utiliser le chat intégré Live Share- Annoncer sur quel fichier vous travaillez- Faire des pauses pour synchroniser
✅ **Sauvegarde** :- Auto-save activé par défaut- Commits fréquents par l'host- Branches pour les gros changements
✅ **Prévisualisation** :- Serveur dev sur `localhost:3000`- Rechargement automatique- Build final avec `npm run build`
## 🔧 Commandes utiles
```bash# Démarrer le serveur de devnpm run dev
# Build pour productionnpm run build
# Exporter en PDFnpm run export:pdf
# Exporter en LaTeXnpm run export:latex
# Voir la previewnpm run preview```
## 🛠️ Résolution de problèmes
### **Live Share ne fonctionne pas ?**```bash# Redémarrer l'extensionCtrl+Shift+P → "Developer: Reload Window"
# Vérifier la connexionCtrl+Shift+P → "Live Share: Show Session Details"```
### **Serveur Astro planté ?**```bash# Redémarrer le serveurCtrl+C # Arrêternpm run dev # Relancer```
### **Conflits Git ?**```bash# L'host gère les commitsgit statusgit add .git commit -m "Collaboration session: [description]"git push```
## 📱 URLs importantes
- **Développement** : `http://localhost:3000`- **Preview** : `http://localhost:8080` - **Repository** : `https://github.com/YOUR_USERNAME/research-article-template`- **Live Space** : `https://huggingface.co/spaces/YOUR_USERNAME/research-template`
## 🎉 Après la session
1. **Host** : Commit et push les changements2. **Tous** : Sync avec `git pull`3. **Deploy** : Push vers HF Space pour mise à jour
---
**💡 Astuce** : Gardez le chat Live Share ouvert pour la coordination en temps réel !7 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950517 unmodified linesheader: miniapp_port: 8080thumbnail: https://huggingface.co/spaces/tfrere/research-paper-template/thumb.jpg---## Find recent duplicated SpacesThis repository includes a small Poetry tool under `tools/duplicated-spaces` to list public Spaces created in the last N days that were duplicated from a given source Space.Setup:```bashcd tools/duplicated-spacespoetry install --no-root```Usage:```bashpoetry run find-duplicated-spaces --source owner/space-name --days 14```Options:- `--source`: required. The source Space in the form `owner/space-name`.- `--days`: optional. Time window in days (default: 14).- `--token`: optional. Your HF token. Defaults to `HF_TOKEN` env var if set.- `--no-deep`: optional. Disable README/frontmatter fallback detection.Examples:```bash# Using env var for the token (optional)export HF_TOKEN=hf_xxx# Find Spaces duplicated from tfrere/my-space in the last 14 dayspoetry run find-duplicated-spaces --source tfrere/my-space# Use a 7-day window and explicit tokenpoetry run find-duplicated-spaces --source tfrere/my-space --days 7 --token $HF_TOKEN```The tool first checks card metadata (e.g., `duplicated_from`) and optionally falls back to parsing the README frontmatter for robustness.7 unmodified lines8910117 unmodified linesheader: miniapp_port: 8080thumbnail: https://huggingface.co/spaces/tfrere/research-paper-template/thumb.jpg---
151 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152168 unmodified lines225226227228229230231232233234235151 unmodified linestype ContentEntryMap = {"chapters": {"best-pratices.mdx": {id: "best-pratices.mdx";slug: "best-pratices";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"components.mdx": {id: "components.mdx";slug: "components";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"debug-components.mdx": {id: "debug-components.mdx";slug: "debug-components";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"getting-started.mdx": {id: "getting-started.mdx";slug: "getting-started";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"greetings.mdx": {id: "greetings.mdx";slug: "greetings";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"introduction.mdx": {id: "introduction.mdx";slug: "introduction";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"markdown.mdx": {id: "markdown.mdx";slug: "markdown";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"vibe-coding-charts.mdx": {id: "vibe-coding-charts.mdx";slug: "vibe-coding-charts";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"writing-your-content.mdx": {id: "writing-your-content.mdx";slug: "writing-your-content";body: string;collection: "chapters";data: any8 unmodified linescollection: "assets";data: any;}>;"embeds": Record<string, {id: string;collection: "embeds";data: any;}>;};151 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082098 unmodified lines218219220221222223151 unmodified linestype ContentEntryMap = {"chapters": {"01_introduction.mdx": {id: "01_introduction.mdx";slug: "01_introduction";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"02_classic_robotics.mdx": {id: "02_classic_robotics.mdx";slug: "02_classic_robotics";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"03_reinforcement_learning.mdx": {id: "03_reinforcement_learning.mdx";slug: "03_reinforcement_learning";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"04_imitation_learning.mdx": {id: "04_imitation_learning.mdx";slug: "04_imitation_learning";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"05_foundation_models.mdx": {id: "05_foundation_models.mdx";slug: "05_foundation_models";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"06_next_directions.mdx": {id: "06_next_directions.mdx";slug: "06_next_directions";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"07_conclusions.mdx": {id: "07_conclusions.mdx";slug: "07_conclusions";body: string;collection: "chapters";data: any} & { render(): Render[".mdx"] };"A_foreword.mdx": {id: "A_foreword.mdx";slug: "a_foreword";body: string;collection: "chapters";data: any8 unmodified linescollection: "assets";data: any;}>;};
56 unmodified lines575859606162636465666768697071727 unmodified lines80818283848586878889909192939495969798991001 unmodified line1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661 unmodified line1681691701711721731742 unmodified lines17717817918018118218334 unmodified lines2182192202212222232243 unmodified lines2282292302312322332342352362371 unmodified line2392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692706 unmodified lines2772782792802812822834 unmodified lines2882892902912922932942952962972981 unmodified line3003013023033043053061 unmodified line30830931031131231331456 unmodified linesfunction extractFrontmatter(content) {const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n/);if (!frontmatterMatch) return { frontmatter: {}, content };const frontmatterText = frontmatterMatch[1];const contentWithoutFrontmatter = content.replace(frontmatterMatch[0], '');// Simple YAML parsing for basic fieldsconst frontmatter = {};const lines = frontmatterText.split('\n');let currentKey = null;let currentValue = '';for (const line of lines) {const trimmed = line.trim();if (trimmed.includes(':') && !trimmed.startsWith('-')) {7 unmodified linescurrentValue += '\n' + trimmed;}}if (currentKey) {frontmatter[currentKey] = currentValue.trim();}return { frontmatter, content: contentWithoutFrontmatter };}function cleanMdxToMarkdown(content) {// Remove import statementscontent = content.replace(/^import .+?;?\s*$/gm, '');// Remove JSX component calls like <ComponentName />content = content.replace(/<[A-Z][a-zA-Z0-9]*\s*\/>/g, '');// Convert JSX components to simpler markdown// Handle Sidenote components speciallycontent = content.replace(/<Sidenote>([\s\S]*?)<\/Sidenote>/g, (match, innerContent) => {1 unmodified lineconst asideMatch = innerContent.match(/<Fragment slot="aside">([\s\S]*?)<\/Fragment>/);const mainContent = innerContent.replace(/<Fragment slot="aside">[\s\S]*?<\/Fragment>/, '').trim();const asideContent = asideMatch ? asideMatch[1].trim() : '';let result = mainContent;if (asideContent) {result += `\n\n> **Note:** ${asideContent}`;}return result;});// Handle Note componentscontent = content.replace(/<Note[^>]*>([\s\S]*?)<\/Note>/g, (match, innerContent) => {return `\n> **Note:** ${innerContent.trim()}\n`;});// Handle Wide and FullWidth componentscontent = content.replace(/<(Wide|FullWidth)>([\s\S]*?)<\/\1>/g, '$2');// Handle HtmlEmbed components (convert to simple text)content = content.replace(/<HtmlEmbed[^>]*\/>/g, '*[Interactive content not available in LaTeX]*');// Remove remaining JSX fragmentscontent = content.replace(/<Fragment[^>]*>([\s\S]*?)<\/Fragment>/g, '$1');content = content.replace(/<[A-Z][a-zA-Z0-9]*[^>]*>([\s\S]*?)<\/[A-Z][a-zA-Z0-9]*>/g, '$1');// Clean up className attributescontent = content.replace(/className="[^"]*"/g, '');// Clean up extra whitespacecontent = content.replace(/\n{3,}/g, '\n\n');return content.trim();}async function processChapterImports(content, contentDir) {let processedContent = content;// First, extract all import statements and their corresponding component callsconst importPattern = /import\s+(\w+)\s+from\s+["']\.\/chapters\/([^"']+)["'];?/g;const imports = new Map();let match;// Collect all importswhile ((match = importPattern.exec(content)) !== null) {const [fullImport, componentName, chapterPath] = match;imports.set(componentName, { path: chapterPath, importStatement: fullImport });}// Remove all import statementsprocessedContent = processedContent.replace(importPattern, '');// Process each component callfor (const [componentName, { path: chapterPath }] of imports) {const componentCallPattern = new RegExp(`<${componentName}\\s*\\/>`, 'g');try {const chapterFile = resolve(contentDir, 'chapters', chapterPath);const chapterContent = await readMdxFile(chapterFile);const { content: chapterMarkdown } = extractFrontmatter(chapterContent);const cleanChapter = cleanMdxToMarkdown(chapterMarkdown);processedContent = processedContent.replace(componentCallPattern, cleanChapter);console.log(`✅ Processed chapter: ${chapterPath}`);} catch (error) {1 unmodified lineprocessedContent = processedContent.replace(componentCallPattern, `\n*[Chapter ${chapterPath} could not be loaded]*\n`);}}return processedContent;}2 unmodified linesconst subtitle = frontmatter.subtitle || '';const authors = frontmatter.authors || '';const date = frontmatter.published || '';return `\\documentclass[11pt,a4paper]{article}\\usepackage[utf8]{inputenc}\\usepackage[T1]{fontenc}34 unmodified linesasync function main() {const cwd = process.cwd();const args = parseArgs(process.argv);// Check if pandoc is installedconst hasPandoc = await checkPandocInstalled();if (!hasPandoc) {3 unmodified linesconsole.error(' Windows: choco install pandoc');process.exit(1);}const contentDir = resolve(cwd, 'src/content');const articleFile = resolve(contentDir, 'article.mdx');// Check if article.mdx existstry {await fs.access(articleFile);1 unmodified lineconsole.error(`❌ Could not find article.mdx at ${articleFile}`);process.exit(1);}console.log('> Reading article content...');const articleContent = await readMdxFile(articleFile);const { frontmatter, content } = extractFrontmatter(articleContent);console.log('> Processing chapters...');const processedContent = await processChapterImports(content, contentDir);console.log('> Converting MDX to Markdown...');const markdownContent = cleanMdxToMarkdown(processedContent);// Generate output filenameconst title = frontmatter.title ? frontmatter.title.replace(/\n/g, ' ') : 'article';const outFileBase = args.filename ? String(args.filename).replace(/\.(tex|pdf)$/i, '') : slugify(title);// Create temporary markdown fileconst tempMdFile = resolve(cwd, 'temp-article.md');await fs.writeFile(tempMdFile, markdownContent);console.log('> Converting to LaTeX with Pandoc...');const outputLatex = resolve(cwd, 'dist', `${outFileBase}.tex`);// Ensure dist directory existsawait fs.mkdir(resolve(cwd, 'dist'), { recursive: true });// Pandoc conversion argumentsconst pandocArgs = [tempMdFile,6 unmodified lines'--highlight-style=tango','--listings'];// Add bibliography if it existsconst bibFile = resolve(contentDir, 'bibliography.bib');try {4 unmodified lines} catch {console.log('ℹ️ No bibliography file found');}try {await run('pandoc', pandocArgs);console.log(`✅ LaTeX generated: ${outputLatex}`);// Optionally compile to PDF if requestedif (args.pdf) {console.log('> Compiling LaTeX to PDF...');1 unmodified lineawait run('pdflatex', ['-output-directory', resolve(cwd, 'dist'), outputLatex]);console.log(`✅ PDF generated: ${outputPdf}`);}} catch (error) {console.error('❌ Pandoc conversion failed:', error.message);process.exit(1);1 unmodified line// Clean up temporary filetry {await fs.unlink(tempMdFile);} catch {}}}56 unmodified lines575859606162636465666768697071727 unmodified lines80818283848586878889909192939495969798991001 unmodified line1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661 unmodified line1681691701711721731742 unmodified lines17717817918018118218334 unmodified lines2182192202212222232243 unmodified lines2282292302312322332342352362371 unmodified line2392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692706 unmodified lines2772782792802812822834 unmodified lines2882892902912922932942952962972981 unmodified line3003013023033043053061 unmodified line30830931031131231331456 unmodified linesfunction extractFrontmatter(content) {const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n/);if (!frontmatterMatch) return { frontmatter: {}, content };const frontmatterText = frontmatterMatch[1];const contentWithoutFrontmatter = content.replace(frontmatterMatch[0], '');// Simple YAML parsing for basic fieldsconst frontmatter = {};const lines = frontmatterText.split('\n');let currentKey = null;let currentValue = '';for (const line of lines) {const trimmed = line.trim();if (trimmed.includes(':') && !trimmed.startsWith('-')) {7 unmodified linescurrentValue += '\n' + trimmed;}}if (currentKey) {frontmatter[currentKey] = currentValue.trim();}return { frontmatter, content: contentWithoutFrontmatter };}function cleanMdxToMarkdown(content) {// Remove import statementscontent = content.replace(/^import .+?;?\s*$/gm, '');// Remove JSX component calls like <ComponentName />content = content.replace(/<[A-Z][a-zA-Z0-9]*\s*\/>/g, '');// Convert JSX components to simpler markdown// Handle Sidenote components speciallycontent = content.replace(/<Sidenote>([\s\S]*?)<\/Sidenote>/g, (match, innerContent) => {1 unmodified lineconst asideMatch = innerContent.match(/<Fragment slot="aside">([\s\S]*?)<\/Fragment>/);const mainContent = innerContent.replace(/<Fragment slot="aside">[\s\S]*?<\/Fragment>/, '').trim();const asideContent = asideMatch ? asideMatch[1].trim() : '';let result = mainContent;if (asideContent) {result += `\n\n> **Note:** ${asideContent}`;}return result;});// Handle Note componentscontent = content.replace(/<Note[^>]*>([\s\S]*?)<\/Note>/g, (match, innerContent) => {return `\n> **Note:** ${innerContent.trim()}\n`;});// Handle Wide and FullWidth componentscontent = content.replace(/<(Wide|FullWidth)>([\s\S]*?)<\/\1>/g, '$2');// Handle HtmlEmbed components (convert to simple text)content = content.replace(/<HtmlEmbed[^>]*\/>/g, '*[Interactive content not available in LaTeX]*');// Remove remaining JSX fragmentscontent = content.replace(/<Fragment[^>]*>([\s\S]*?)<\/Fragment>/g, '$1');content = content.replace(/<[A-Z][a-zA-Z0-9]*[^>]*>([\s\S]*?)<\/[A-Z][a-zA-Z0-9]*>/g, '$1');// Clean up className attributescontent = content.replace(/className="[^"]*"/g, '');// Clean up extra whitespacecontent = content.replace(/\n{3,}/g, '\n\n');return content.trim();}async function processChapterImports(content, contentDir) {let processedContent = content;// First, extract all import statements and their corresponding component callsconst importPattern = /import\s+(\w+)\s+from\s+["']\.\/chapters\/([^"']+)["'];?/g;const imports = new Map();let match;// Collect all importswhile ((match = importPattern.exec(content)) !== null) {const [fullImport, componentName, chapterPath] = match;imports.set(componentName, { path: chapterPath, importStatement: fullImport });}// Remove all import statementsprocessedContent = processedContent.replace(importPattern, '');// Process each component callfor (const [componentName, { path: chapterPath }] of imports) {const componentCallPattern = new RegExp(`<${componentName}\\s*\\/>`, 'g');try {const chapterFile = resolve(contentDir, 'chapters', chapterPath);const chapterContent = await readMdxFile(chapterFile);const { content: chapterMarkdown } = extractFrontmatter(chapterContent);const cleanChapter = cleanMdxToMarkdown(chapterMarkdown);processedContent = processedContent.replace(componentCallPattern, cleanChapter);console.log(`✅ Processed chapter: ${chapterPath}`);} catch (error) {1 unmodified lineprocessedContent = processedContent.replace(componentCallPattern, `\n*[Chapter ${chapterPath} could not be loaded]*\n`);}}return processedContent;}2 unmodified linesconst subtitle = frontmatter.subtitle || '';const authors = frontmatter.authors || '';const date = frontmatter.published || '';return `\\documentclass[11pt,a4paper]{article}\\usepackage[utf8]{inputenc}\\usepackage[T1]{fontenc}34 unmodified linesasync function main() {const cwd = process.cwd();const args = parseArgs(process.argv);// Check if pandoc is installedconst hasPandoc = await checkPandocInstalled();if (!hasPandoc) {3 unmodified linesconsole.error(' Windows: choco install pandoc');process.exit(1);}const contentDir = resolve(cwd, 'src/content');const articleFile = resolve(contentDir, 'article.mdx');// Check if article.mdx existstry {await fs.access(articleFile);1 unmodified lineconsole.error(`❌ Could not find article.mdx at ${articleFile}`);process.exit(1);}console.log('> Reading article content...');const articleContent = await readMdxFile(articleFile);const { frontmatter, content } = extractFrontmatter(articleContent);console.log('> Processing chapters...');const processedContent = await processChapterImports(content, contentDir);console.log('> Converting MDX to Markdown...');const markdownContent = cleanMdxToMarkdown(processedContent);// Generate output filenameconst title = frontmatter.title ? frontmatter.title.replace(/\n/g, ' ') : 'article';const outFileBase = args.filename ? String(args.filename).replace(/\.(tex|pdf)$/i, '') : slugify(title);// Create temporary markdown fileconst tempMdFile = resolve(cwd, 'temp-article.md');await fs.writeFile(tempMdFile, markdownContent);console.log('> Converting to LaTeX with Pandoc...');const outputLatex = resolve(cwd, 'dist', `${outFileBase}.tex`);// Ensure dist directory existsawait fs.mkdir(resolve(cwd, 'dist'), { recursive: true });// Pandoc conversion argumentsconst pandocArgs = [tempMdFile,6 unmodified lines'--highlight-style=tango','--listings'];// Add bibliography if it existsconst bibFile = resolve(contentDir, 'bibliography.bib');try {4 unmodified lines} catch {console.log('ℹ️ No bibliography file found');}try {await run('pandoc', pandocArgs);console.log(`✅ LaTeX generated: ${outputLatex}`);// Optionally compile to PDF if requestedif (args.pdf) {console.log('> Compiling LaTeX to PDF...');1 unmodified lineawait run('pdflatex', ['-output-directory', resolve(cwd, 'dist'), outputLatex]);console.log(`✅ PDF generated: ${outputPdf}`);}} catch (error) {console.error('❌ Pandoc conversion failed:', error.message);process.exit(1);1 unmodified line// Clean up temporary filetry {await fs.unlink(tempMdFile);} catch { }}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107# Convertisseur LaTeX vers Markdown
Conversion robuste de projets LaTeX complexes vers Markdown/MDX pour Astro.
## 🚀 Usage rapide
```bash# Conversion standardnode scripts/latex-converter/index.mjs
# Avec nettoyage du dossier de sortienode scripts/latex-converter/index.mjs --clean
# Chemins personnalisésnode scripts/latex-converter/index.mjs \ --input=../tools/latex-to-markdown/input \ --output=src/content \ --clean```
## 📁 Architecture
```scripts/latex-converter/├── index.mjs # Point d'entrée principal├── config.mjs # Configuration et mappings├── preprocessor.mjs # Préprocesseur LaTeX├── bibliography-cleaner.mjs # Nettoyeur de bibliographie├── converter.mjs # Convertisseur principal└── README.md # Documentation```
## 🔧 Fonctionnalités
### ✅ Ce qui est géré- **412+ commandes personnalisées** (math, text, projet-spécifique)- **Environnements custom** (`tldr`, `callout`, `finding`)- **41 figures** avec organisation par chapitre- **2247 entrées bibliographiques** avec nettoyage automatique- **Citations** et références croisées- **Structure MDX** compatible Astro
### 🛠️ Transformations automatiques
#### Commandes LaTeX → Markdown```latex\lerobot → **LeRobot**\lerobotdataset → `LeRobotDataset`\huggingface → 🤗 **Hugging Face**\eg → e.g.,\X → \mathcal{X}```
#### Environnements → Callouts```latex\begin{tldr}Content here\end{tldr}```→```markdown> **TL;DR**> Content here```
#### Bibliographie- `{{Title}}` → `Title` (suppression doubles accolades)- `\&` → `&` (déséchappement)- Nettoyage général du formatting
## 📊 Statistiques exemple
```⏱️ Time: 1.02s📄 Files: 9 sections converties🖼️ Figures: 41 images copiées📚 Citations: Detection automatique🔧 Commands replaced: 34 transformations📦 Environments processed: 4 environnements📚 Bibliography: 159 entries, 403 fixes```
## 🎯 Résultat
Structure finale dans `src/content/`:```src/content/├── article.mdx # Article principal avec imports├── bibliography.bib # Bibliographie nettoyée├── chapters/ # Sections converties│ ├── 00_abstract.mdx│ ├── 01_introduction.mdx│ └── ...└── assets/image/ # Figures organisées ├── ch1/ ├── ch2/ └── ...```
## ⚠️ Prérequis
- **Pandoc** installé (`brew install pandoc`)- Node.js avec support ESM
## 🔍 Debugging
Les warnings sont normaux pour les sections avec math complexe non supporté par Pandoc. Le convertisseur continue et produit un résultat utilisable.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123/** * Nettoyeur de bibliographie - Corrige les doubles accolades et problèmes de formatting */
export class BibliographyCleaner { constructor() { this.stats = { entriesProcessed: 0, doubleAccoladesFixed: 0, escapedCharsFixed: 0, mathExpressionsFixed: 0 }; }
cleanContent(content) { let cleaned = content;
// Count entries this.stats.entriesProcessed = (content.match(/@\w+\{/g) || []).length;
// Fix double accolades cleaned = this.fixDoubleAccolades(cleaned);
// Fix escaped characters cleaned = this.fixEscapedCharacters(cleaned);
// Fix malformed math expressions cleaned = this.fixMathExpressions(cleaned);
// General cleanup cleaned = this.generalCleanup(cleaned);
return cleaned; }
fixDoubleAccolades(content) { let fixed = content; let fixCount = 0;
fixed = fixed.replace(/\{\{([^}]+)\}\}/g, (match, inner) => { fixCount++;
// Keep accolades for important terms if (/^[A-Z][A-Z0-9]*$/.test(inner) || // Acronyms like "API", "ML" /^[A-Z][a-z]*(?:\s+[A-Z][a-z]*)*$/.test(inner) || // Proper nouns inner.includes('++') || // Languages like "C++" inner.includes('$') // Math ) { return `{${inner}}`; }
return inner; });
this.stats.doubleAccoladesFixed = fixCount; return fixed; }
fixEscapedCharacters(content) { let fixed = content; let fixCount = 0;
const replacements = [ [/\\&/g, '&'], [/\\\$/g, '$'], [/\\%/g, '%'], [/\\#/g, '#'], [/\\_/g, '_'] ];
for (const [pattern, replacement] of replacements) { const matches = fixed.match(pattern); if (matches) { fixCount += matches.length; fixed = fixed.replace(pattern, replacement); } }
this.stats.escapedCharsFixed = fixCount; return fixed; }
fixMathExpressions(content) { let fixed = content; let fixCount = 0;
// Fix specific problematic patterns const mathFixes = [ // ${$\pi_$}0$ → $\pi_0$ [/\$\{\$\\pi_\$\}([0-9]+)\$/g, '$\\pi_$1$'], // ${$something$}text$ → $something_text$ [/\$\{\$([^}]+)\$\}([^$]*)\$/g, '$$$1_$2$$'], // Fix other malformed patterns [/\$\{([^}]+)\}\$/g, '$$$1$$'], [/\$([^$]*)\\\$([^$]*)\$/g, '$$$1$2$$'] ];
for (const [pattern, replacement] of mathFixes) { const matches = fixed.match(pattern); if (matches) { fixCount += matches.length; fixed = fixed.replace(pattern, replacement); } }
this.stats.mathExpressionsFixed = fixCount; return fixed; }
generalCleanup(content) { let cleaned = content;
// Normalize whitespace cleaned = cleaned.replace(/\n{3,}/g, '\n\n'); cleaned = cleaned.trim() + '\n';
return cleaned; }
getStats() { return this.stats; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/** * Configuration et mappings pour la conversion LaTeX vers Markdown */
export const COMMAND_MAPPINGS = { // Math shortcuts 'X': '\\mathcal{X}', 'Z': '\\mathcal{Z}', 'G': '\\mathcal{G}', 'D': '\\mathcal{D}', 'F': '\\mathcal{F}', 'R': '\\mathcal{R}',
// Text commands 'eg': 'e.g.,', 'ie': 'i.e.,', 'versus': 'vs.', 'wrt': 'w.r.t.', 'etc': 'etc.',
// Project-specific 'lerobot': '**LeRobot**', 'lerobotdataset': '`LeRobotDataset`', 'huggingface': '🤗 **Hugging Face**',
// Functions 'qfunction': 'Q-function', 'qopt': 'Q^*'};
export const ENVIRONMENT_MAPPINGS = { 'tldr': { start: '> **TL;DR**\n> ', end: '\n', type: 'callout' }, 'callout': { start: '> **Note**\n> ', end: '\n', type: 'callout' }, 'finding': { start: '> **🔍 Finding**: ', end: '\n', type: 'finding' }};
export const PANDOC_OPTIONS = [ '--from=latex', '--to=markdown', '--wrap=preserve', '--markdown-headings=atx'];
export const DEFAULT_PATHS = { input: '../tools/latex-to-markdown/input', output: 'src/content'};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456/** * Convertisseur principal LaTeX vers Markdown */
import { spawn } from 'node:child_process';import { promises as fs } from 'node:fs';import { resolve, dirname, basename, join } from 'node:path';
import { LaTeXPreprocessor } from './preprocessor.mjs';import { RobustLaTeXPreprocessor } from './robust-preprocessor.mjs';import { BibliographyCleaner } from './bibliography-cleaner.mjs';import { DEFAULT_PATHS, PANDOC_OPTIONS } from './config.mjs';
export class LaTeXConverter { constructor() { this.preprocessor = new LaTeXPreprocessor(); this.robustPreprocessor = new RobustLaTeXPreprocessor(); this.bibCleaner = new BibliographyCleaner(); this.stats = { totalFiles: 0, totalFigures: 0, totalCitations: 0, conversionTime: 0 }; this.warnings = []; this.errors = []; }
async convert(inputDir, outputDir, options = {}) { const startTime = Date.now();
console.log('🚀 LaTeX to Markdown Converter'); console.log(`📁 Input: ${inputDir}`); console.log(`📁 Output: ${outputDir}`);
try { // Setup await this.setupOutput(outputDir, options.clean);
// Convert sections await this.convertSections(inputDir, outputDir);
// Handle assets await this.handleAssets(inputDir, outputDir);
// Create main article await this.createMainArticle(outputDir);
// Generate report this.stats.conversionTime = Date.now() - startTime; this.generateReport();
console.log('🎉 Conversion completed successfully!'); return true;
} catch (error) { this.errors.push(`Conversion failed: ${error.message}`); throw error; } }
async setupOutput(outputDir, clean = false) { if (clean) { console.log('🧹 Cleaning output directory...'); await fs.rm(outputDir, { recursive: true, force: true }); }
await fs.mkdir(outputDir, { recursive: true }); await fs.mkdir(join(outputDir, 'chapters'), { recursive: true }); await fs.mkdir(join(outputDir, 'assets', 'image'), { recursive: true }); }
async convertSections(inputDir, outputDir) { console.log('\n📄 Converting sections...');
const sectionsDir = join(inputDir, 'sections'); const outputChaptersDir = join(outputDir, 'chapters');
try { const files = await fs.readdir(sectionsDir); const texFiles = files.filter(f => f.endsWith('.tex'));
for (const file of texFiles) { const inputPath = join(sectionsDir, file); const outputPath = join(outputChaptersDir, file.replace('.tex', '.mdx'));
console.log(` Converting ${file}...`); await this.convertSingleFile(inputPath, outputPath); }
this.stats.totalFiles = texFiles.length;
} catch (error) { this.errors.push(`Section conversion failed: ${error.message}`); } }
async convertSingleFile(inputPath, outputPath) { try { // Read and preprocess with robust preprocessor let content = await fs.readFile(inputPath, 'utf-8'); content = this.robustPreprocessor.preprocessContent(content, basename(inputPath));
// Create temp file for Pandoc const tempPath = inputPath + '.temp'; await fs.writeFile(tempPath, content);
// Convert with Pandoc const pandocArgs = [tempPath, '-o', outputPath, ...PANDOC_OPTIONS]; await this.runPandoc(pandocArgs);
// Cleanup await fs.unlink(tempPath);
// Post-process await this.postProcessFile(outputPath);
} catch (error) { this.warnings.push(`Failed to convert ${basename(inputPath)}: ${error.message}`); } }
async runPandoc(args) { return new Promise((resolve, reject) => { const child = spawn('pandoc', args, { stdio: ['pipe', 'pipe', 'pipe'], shell: false });
let stderr = ''; child.stderr.on('data', (data) => { stderr += data.toString(); });
child.on('error', reject); child.on('exit', (code) => { if (code === 0) { resolve(); } else { reject(new Error(`Pandoc failed: ${stderr}`)); } }); }); }
fixMalformedMath(content) { let fixed = content;
// Fix problematic expressions like ${$\pi_$}0$ fixed = fixed.replace(/\$\{\$([^$}]+)\$\}([^$]*)\$/g, '$$$1_{$2}$$');
// Fix nested math delimiters fixed = fixed.replace(/\$\$([^$]*)\$([^$]*)\$([^$]*)\$\$/g, '$$$1 $2 $3$$');
// Fix incomplete math expressions fixed = fixed.replace(/\$([^$]*)\{([^}]*)\$([^$]*)\$/g, '$$$1\\{$2\\}$3$$');
// Fix math with unescaped braces fixed = fixed.replace(/\$([^$]*)\{([^}]*)\}([^$]*)\$/g, '$$$1\\{$2\\}$3$$');
// Fix common pi expressions fixed = fixed.replace(/\$\\pi_\$([0-9]+)\$/g, '$\\pi_$1$'); fixed = fixed.replace(/\$\{\\pi_\}([0-9]+)\$/g, '$\\pi_$1$');
// Fix doubled dollar signs (but preserve display math) fixed = fixed.replace(/\$\$\$+/g, '$$');
// Ensure proper spacing around math fixed = fixed.replace(/([a-zA-Z])\$([^$]+)\$([a-zA-Z])/g, '$1 $$$2$$ $3');
return fixed; }
fixMDXUrls(content) { let fixed = content;
// Fix all escaped markdown that should be unescaped for MDX fixed = fixed.replace(/\\\*/g, '*'); fixed = fixed.replace(/\\\[/g, '['); fixed = fixed.replace(/\\\]/g, ']'); fixed = fixed.replace(/\\\(/g, '('); fixed = fixed.replace(/\\\)/g, ')'); fixed = fixed.replace(/\\>/g, '>'); fixed = fixed.replace(/\\!/g, '!');
// Fix angle bracket URLs that are MDX-incompatible fixed = fixed.replace(/\*\*<(https?:\/\/[^>]+)>\*\*/g, '**[$1]($1)**'); fixed = fixed.replace(/<(https?:\/\/[^>]+)>/g, '[$1]($1)');
// Fix malformed math expressions with escaped braces fixed = fixed.replace(/\\\{/g, '{'); fixed = fixed.replace(/\\\}/g, '}');
// Escape all braces in math expressions for MDX compatibility fixed = fixed.replace(/\$([^$]*)\$/g, (match, mathContent) => { const escaped = mathContent.replace(/\{/g, '\\{').replace(/\}/g, '\\}'); return `$${escaped}$`; });
fixed = fixed.replace(/\$\$([^$]*)\$\$/g, (match, mathContent) => { const escaped = mathContent.replace(/\{/g, '\\{').replace(/\}/g, '\\}'); return `$$${escaped}$$`; });
// Fix Section references that are malformed fixed = fixed.replace(/Section\s+([a-zA-Z-]+:[a-zA-Z0-9-]+)\\/g, 'the referenced figure'); fixed = fixed.replace(/Figure\s+Section\s+([a-zA-Z-]+:[a-zA-Z0-9-]+)\\/g, 'the referenced figure');
return fixed; }
async postProcessFile(filePath) { try { let content = await fs.readFile(filePath, 'utf-8');
// Fix common issues content = content.replace(/\\\\#/g, '#'); content = content.replace(/\\\\!/g, '!'); content = content.replace(/\\\\\*/g, '*');
// Fix citations content = content.replace(/\\citep\{([^}]+)\}/g, '[@$1]'); content = content.replace(/\\citet\{([^}]+)\}/g, '@$1'); content = content.replace(/\\cite\{([^}]+)\}/g, '[@$1]');
// Remove section labels from headers content = content.replace(/^(#{1,6}.*?)\s*\{#[^}]+\}/gm, '$1');
// Fix complex LaTeX references like [\[sec:xxx\]](#sec:xxx){reference-type="ref" reference="sec:xxx"} content = content.replace(/\[\\?\[([^\]]+)\\?\]\]\(#[^)]+\)\{[^}]*reference[^}]*\}/g, 'Section $1');
// Fix simple references [\[ref\]](#ref) content = content.replace(/\[\\?\[([^\]]+)\\?\]\]\(#[^)]+\)/g, '$1');
// Fix remaining malformed references like "Section Section sec:classical\" content = content.replace(/Section\s+Section\s+([^\\]+)\\/g, 'Section $1'); content = content.replace(/Section\s+Section\s+([^\\]+)/g, 'Section $1');
// Remove remaining LaTeX labels and references content = content.replace(/\\label\{[^}]+\}/g, ''); content = content.replace(/\\ref\{[^}]+\}/g, '[Reference]');
// Clean up section references with colons (be more specific) content = content.replace(/Section\s+sec:([a-zA-Z-]+)/g, 'the following section');
// Fix broken section references that got mangled content = content.replace(/Section\s+secs[a-zA-Z]*\s+/g, 'The following section '); content = content.replace(/Section\s+sec[a-zA-Z]*\s+/g, 'The following section ');
// Count citations const citations = content.match(/\[@[^\]]+\]/g) || []; this.stats.totalCitations += citations.length;
// Fix malformed math expressions content = this.fixMalformedMath(content);
// Fix MDX-incompatible URLs (post-pandoc) content = this.fixMDXUrls(content);
// Final cleanup content = content.replace(/\n{3,}/g, '\n\n'); content = content.replace(/\\texttt\{([^}]+)\}/g, '`$1`'); content = content.replace(/\\textbf\{([^}]+)\}/g, '**$1**'); content = content.replace(/\\emph\{([^}]+)\}/g, '*$1*'); content = content.trim();
await fs.writeFile(filePath, content);
} catch (error) { this.warnings.push(`Post-processing failed for ${basename(filePath)}: ${error.message}`); } }
async handleAssets(inputDir, outputDir) { console.log('\n🖼️ Handling assets...');
// Copy figures try { const figuresInputDir = join(inputDir, 'figures'); const assetsOutputDir = join(outputDir, 'assets', 'image');
await this.copyDirectoryRecursive(figuresInputDir, assetsOutputDir); this.stats.totalFigures = await this.countFiles(assetsOutputDir, /\.(png|jpg|jpeg|pdf|svg)$/i);
console.log(` 📊 Copied ${this.stats.totalFigures} figures`); } catch (error) { this.warnings.push(`Could not copy figures: ${error.message}`); }
// Handle bibliography try { const bibPath = join(inputDir, 'main.bib'); const outputBibPath = join(outputDir, 'bibliography.bib');
// Copy and clean bibliography let bibContent = await fs.readFile(bibPath, 'utf-8'); bibContent = this.bibCleaner.cleanContent(bibContent); await fs.writeFile(outputBibPath, bibContent);
const bibStats = this.bibCleaner.getStats(); console.log(` 📚 Bibliography: ${bibStats.entriesProcessed} entries, ${bibStats.doubleAccoladesFixed} fixes, ${bibStats.mathExpressionsFixed} math fixes`);
} catch (error) { this.warnings.push(`Could not handle bibliography: ${error.message}`); } }
async copyDirectoryRecursive(src, dest) { await fs.mkdir(dest, { recursive: true }); const entries = await fs.readdir(src, { withFileTypes: true });
for (const entry of entries) { const srcPath = join(src, entry.name); const destPath = join(dest, entry.name);
if (entry.isDirectory()) { await this.copyDirectoryRecursive(srcPath, destPath); } else { await fs.copyFile(srcPath, destPath); } } }
async countFiles(dir, pattern) { let count = 0; try { const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) { if (entry.isDirectory()) { count += await this.countFiles(join(dir, entry.name), pattern); } else if (pattern.test(entry.name)) { count++; } } } catch { // Directory doesn't exist }
return count; }
async createMainArticle(outputDir) { console.log('\n📝 Creating main article...');
try { const chaptersDir = join(outputDir, 'chapters'); const files = await fs.readdir(chaptersDir); const mdxFiles = files.filter(f => f.endsWith('.mdx')).sort();
const frontmatter = this.generateFrontmatter(); const { imports, components } = this.generateChapterImports(mdxFiles);
const articleContent = frontmatter + imports + '\n\n' + components;
const articlePath = join(outputDir, 'article.mdx'); await fs.writeFile(articlePath, articleContent);
console.log(` 📄 Created article.mdx with ${mdxFiles.length} chapters`);
} catch (error) { this.errors.push(`Failed to create main article: ${error.message}`); } }
generateFrontmatter() { const now = new Date().toISOString().split('T')[0];
return `---title: "Robot Learning: A Tutorial"subtitle: "From Classical Robotics to Foundation Models"description: "A comprehensive guide to modern robot learning techniques"date: "${now}"authors: - name: "Francesco Capuano" affiliations: [1, 2] - name: "Adil Zouitine" affiliations: [2] - name: "Pepijn Kooijmans" affiliations: [2] - name: "Thomas Wolf" affiliations: [2] - name: "Michel Aractingi" affiliations: [2]affiliations: - name: "École Normale Supérieure Paris-Saclay" url: "https://ens-paris-saclay.fr" - name: "Hugging Face" url: "https://huggingface.co"tags: - robotics - machine-learning - tutorialbibliography: bibliography.bibconverted_from: "LaTeX"---
`; }
generateChapterImports(mdxFiles) { let imports = ''; let components = '';
mdxFiles.forEach(file => { const sectionName = basename(file, '.mdx'); const componentName = this.formatComponentName(sectionName);
imports += `import ${componentName} from "./chapters/${sectionName}.mdx";\n`; components += `<${componentName} />\n\n`; });
return { imports, components }; }
formatComponentName(sectionName) { let componentName = sectionName .split(/[_-]/) .map(part => part.charAt(0).toUpperCase() + part.slice(1)) .join('');
if (/^\d/.test(componentName)) { componentName = 'Chapter' + componentName; }
if (componentName === 'AForword') componentName = 'Foreword'; if (componentName === 'Chapter00Abstract') componentName = 'Abstract';
return componentName; }
generateReport() { console.log('\n📊 Conversion Report:'); console.log('====================='); console.log(`⏱️ Time: ${(this.stats.conversionTime / 1000).toFixed(2)}s`); console.log(`📄 Files: ${this.stats.totalFiles}`); console.log(`🖼️ Figures: ${this.stats.totalFigures}`); console.log(`📚 Citations: ${this.stats.totalCitations}`); console.log(`⚠️ Warnings: ${this.warnings.length}`); console.log(`❌ Errors: ${this.errors.length}`);
const robustStats = this.robustPreprocessor.getStats(); console.log(`🔧 Commands replaced: ${robustStats.commandsReplaced}`); console.log(`📦 Environments processed: ${robustStats.environmentsProcessed}`); console.log(`🖼️ Figures processed: ${robustStats.figuresProcessed}`); console.log(`📐 Math expressions fixed: ${robustStats.mathExpressionsFixed}`);
if (this.warnings.length > 0 && this.warnings.length <= 3) { console.log('\n⚠️ Warnings:'); this.warnings.forEach(w => console.log(` - ${w}`)); } else if (this.warnings.length > 3) { console.log(`\n⚠️ ${this.warnings.length} warnings:`); this.warnings.forEach(w => console.log(` - ${w.substring(0, 150)}...`)); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179/** * Transformateur d'images : Markdown → ResponsiveImage Astro * Convertit les images markdown en composants ResponsiveImage optimisés */
import { promises as fs } from 'node:fs';import { dirname, basename, extname, resolve, relative } from 'node:path';
export class ImageTransformer { constructor() { this.stats = { filesProcessed: 0, imagesTransformed: 0, importsAdded: 0 }; }
async transformImagesInDirectory(contentDir) { const chaptersDir = resolve(contentDir, 'chapters');
try { const files = await fs.readdir(chaptersDir); const mdxFiles = files.filter(file => file.endsWith('.mdx'));
for (const file of mdxFiles) { const filePath = resolve(chaptersDir, file); await this.transformImagesInFile(filePath, contentDir); this.stats.filesProcessed++; }
console.log(`📸 Image transformation completed:`); console.log(` 📄 Files processed: ${this.stats.filesProcessed}`); console.log(` 🖼️ Images transformed: ${this.stats.imagesTransformed}`); console.log(` 📦 Imports added: ${this.stats.importsAdded}`);
} catch (error) { console.error('Error transforming images:', error.message); } }
async transformImagesInFile(filePath, contentDir) { try { let content = await fs.readFile(filePath, 'utf-8');
const imageInfo = this.extractImageInfo(content); if (imageInfo.length === 0) { return; // No images to transform }
const imports = this.generateImports(imageInfo, filePath, contentDir); const transformedContent = this.transformImageReferences(content, imageInfo);
// Add imports at the top of the file const finalContent = this.addImportsToFile(transformedContent, imports);
await fs.writeFile(filePath, finalContent);
this.stats.imagesTransformed += imageInfo.length; this.stats.importsAdded += imports.length;
} catch (error) { console.error(`Error processing ${filePath}:`, error.message); } }
extractImageInfo(content) { // More robust regex that handles complex alt text with brackets and parentheses const imageRegex = /!\[([^\]]*(?:\[[^\]]*\][^\]]*)*)\]\(([^)]+)\)(?:\s*(#[^\s]+))?/g; const images = []; let match;
while ((match = imageRegex.exec(content)) !== null) { const [fullMatch, alt, src, id] = match;
// Only process relative image paths (not external URLs) if (!src.startsWith('http') && !src.startsWith('//')) { images.push({ fullMatch, alt: alt || 'Figure', src, id: id ? id.substring(1) : null, // Remove # from id variableName: this.generateVariableName(src) }); } }
return images; }
generateVariableName(imagePath) { // Convert path to valid variable name // assets/image/ch4/ch4-bc-trajectories.png → ch4BcTrajectories const filename = basename(imagePath, extname(imagePath));
return filename .replace(/[-_]/g, ' ') .replace(/\b\w/g, l => l.toUpperCase()) .replace(/\s/g, '') .replace(/^\d+/, 'Fig$&'); // Prefix with Fig if starts with number }
generateImports(imageInfo, filePath, contentDir) { const imports = [];
// Add ResponsiveImage import imports.push("import ResponsiveImage from '../../components/ResponsiveImage.astro'");
// Add image imports for (const image of imageInfo) { const relativePath = this.getRelativeImagePath(image.src, filePath, contentDir); imports.push(`import ${image.variableName} from '${relativePath}'`); }
return imports; }
getRelativeImagePath(imageSrc, filePath, contentDir) { // Convert absolute image path to relative from chapter file // From: chapters/04_imitation_learning.mdx // To: ../assets/image/ch4/ch4-bc-trajectories.png
const chapterDir = dirname(filePath); const imageAbsolutePath = resolve(contentDir, imageSrc); const relativePath = relative(chapterDir, imageAbsolutePath);
return relativePath.startsWith('.') ? relativePath : `./${relativePath}`; }
transformImageReferences(content, imageInfo) { let transformed = content;
for (const image of imageInfo) { const componentTag = this.generateResponsiveImageTag(image); transformed = transformed.replace(image.fullMatch, componentTag); }
return transformed; }
generateResponsiveImageTag(image) { const props = [ `src={${image.variableName}}`, `alt="${image.alt}"` ];
if (image.id) { props.push(`id="${image.id}"`); }
return `<ResponsiveImage ${props.join(' ')} />`; }
addImportsToFile(content, imports) { if (imports.length === 0) { return content; }
// Check if there are already imports at the top const lines = content.split('\n'); let insertIndex = 0;
// Skip existing imports while (insertIndex < lines.length && (lines[insertIndex].startsWith('import ') || lines[insertIndex].trim() === '')) { insertIndex++; }
// Insert imports const importBlock = imports.join('\n') + '\n\n'; lines.splice(insertIndex, 0, importBlock);
return lines.join('\n'); }
getStats() { return this.stats; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#!/usr/bin/env node/** * Point d'entrée principal pour la conversion LaTeX vers Markdown * * Usage: node scripts/latex-converter/index.mjs [--input=path] [--output=path] [--clean] */
import { resolve } from 'node:path';import { spawn } from 'node:child_process';import process from 'node:process';
import { LaTeXConverter } from './converter.mjs';import { ImageTransformer } from './image-transformer.mjs';import { DEFAULT_PATHS } from './config.mjs';
function parseArgs(argv) { const out = {}; for (const arg of argv.slice(2)) { if (!arg.startsWith('--')) continue; const [k, v] = arg.replace(/^--/, '').split('='); out[k] = v === undefined ? true : v; } return out;}
async function checkPandoc() { try { const child = spawn('pandoc', ['--version'], { stdio: 'pipe' }); return new Promise((resolve) => { child.on('exit', (code) => resolve(code === 0)); child.on('error', () => resolve(false)); }); } catch { return false; }}
async function main() { const cwd = process.cwd(); const args = parseArgs(process.argv);
// Vérifier Pandoc const hasPandoc = await checkPandoc(); if (!hasPandoc) { console.error('❌ Pandoc n\'est pas installé.'); console.error(' macOS: brew install pandoc'); console.error(' Ubuntu: apt-get install pandoc'); process.exit(1); }
// Chemins const inputDir = resolve(cwd, args.input || DEFAULT_PATHS.input); const outputDir = resolve(cwd, args.output || DEFAULT_PATHS.output);
try { const converter = new LaTeXConverter(); await converter.convert(inputDir, outputDir, { clean: args.clean || false });
// Transform images to ResponsiveImage components console.log('\n📸 Transforming images to ResponsiveImage components...'); const imageTransformer = new ImageTransformer(); await imageTransformer.transformImagesInDirectory(outputDir);
} catch (error) { console.error('❌ Conversion échouée:', error.message); process.exit(1); }}
main().catch(err => { console.error('❌ Erreur fatale:', err); process.exit(1);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115/** * Préprocesseur LaTeX - Nettoie et simplifie le contenu LaTeX */
import { COMMAND_MAPPINGS, ENVIRONMENT_MAPPINGS } from './config.mjs';
export class LaTeXPreprocessor { constructor() { this.stats = { commandsReplaced: 0, environmentsProcessed: 0, figuresFixed: 0 }; }
preprocessContent(content) { let processed = content;
// Remove comments processed = processed.replace(/%.*$/gm, '');
// Apply command mappings processed = this.applyCommandMappings(processed);
// Process custom environments processed = this.processCustomEnvironments(processed);
// Fix figures processed = this.fixFigures(processed);
// General cleanup processed = processed.replace(/\n{3,}/g, '\n\n'); processed = processed.trim();
return processed; }
applyCommandMappings(content) { let processed = content;
for (const [command, replacement] of Object.entries(COMMAND_MAPPINGS)) { const regex = new RegExp(`\\\\${command.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![a-zA-Z])`, 'g'); const matches = processed.match(regex); if (matches) { this.stats.commandsReplaced += matches.length; processed = processed.replace(regex, replacement); } }
return processed; }
processCustomEnvironments(content) { let processed = content;
// Convert tldr environment processed = processed.replace( /\\begin\{tldr\}(.*?)\\end\{tldr\}/gs, (match, content) => { this.stats.environmentsProcessed++; return `> **TL;DR**\n> ${content.trim()}\n`; } );
// Convert callout environment processed = processed.replace( /\\begin\{callout\}\{([^}]*)\}(.*?)\\end\{callout\}/gs, (match, title, content) => { this.stats.environmentsProcessed++; return `> **${title}**\n> ${content.trim()}\n`; } );
// Convert finding environment processed = processed.replace( /\\finding\{([^}]*)\}\{([^}]*)\}/g, (match, number, content) => { this.stats.environmentsProcessed++; return `> **🔍 Finding ${number}**: ${content}\n`; } );
return processed; }
fixFigures(content) { let fixed = content;
// Fix complex figure environments const figurePattern = /\\begin\{figure\}[\s\S]*?\\includegraphics(?:\[[^\]]*\])?\{([^}]+)\}[\s\S]*?\\caption\{([^}]+)\}[\s\S]*?(?:\\label\{([^}]+)\})?[\s\S]*?\\end\{figure\}/g;
fixed = fixed.replace(figurePattern, (match, imagePath, caption, label) => { this.stats.figuresFixed++; const cleanPath = imagePath.replace(/^figures\//, 'assets/image/'); const labelAttr = label ? ` {#fig-${label}}` : ''; return `\n${labelAttr}\n\n*${caption}*\n`; });
// Fix simple includegraphics fixed = fixed.replace( /\\includegraphics(?:\[[^\]]*\])?\{([^}]+)\}/g, (match, imagePath) => { this.stats.figuresFixed++; const cleanPath = imagePath.replace(/^figures\//, 'assets/image/'); return ``; } );
return fixed; }
getStats() { return this.stats; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399/** * Préprocesseur LaTeX Ultra-Robuste * Gère les cas complexes qui font planter Pandoc */
export class RobustLaTeXPreprocessor { constructor() { this.stats = { figuresProcessed: 0, citationsFixed: 0, mathExpressionsFixed: 0, environmentsProcessed: 0, commandsReplaced: 0 }; this.debugMode = false; }
preprocessContent(content, filename = 'unknown') { if (this.debugMode) { console.log(` 🔍 [DEBUG] Processing ${filename}...`); }
let processed = content;
// Phase 1: Structure cleanup (most important first) processed = this.phase1_StructureCleanup(processed);
// Phase 2: Content transformation processed = this.phase2_ContentTransformation(processed);
// Phase 3: Final polish processed = this.phase3_FinalPolish(processed);
return processed; }
phase1_StructureCleanup(content) { let cleaned = content;
// Remove comments (but preserve structure) cleaned = cleaned.replace(/%.*$/gm, '');
// Fix broken line breaks that split words cleaned = this.fixBrokenLineBreaks(cleaned);
// Fix broken equation environments cleaned = this.fixBrokenEquations(cleaned);
// Fix broken figure environments BEFORE processing cleaned = this.fixComplexFigures(cleaned);
// Handle problematic environments early cleaned = this.handleProblematicEnvironments(cleaned);
return cleaned; }
fixBrokenLineBreaks(content) { let fixed = content;
// Fix hyphenated words broken across lines // "length-\nT\nT" → "length-T" fixed = fixed.replace(/([a-zA-Z])-\s*\n\s*([A-Z])\s*\n\s*\2/g, '$1-$2');
// Fix broken compound words // "some-\nword" → "some-word" fixed = fixed.replace(/([a-zA-Z])-\s*\n\s*([a-z])/g, '$1-$2');
// Fix sentences that got broken inappropriately // "word.Sentence" → "word. Sentence" fixed = fixed.replace(/([a-z])\.([A-Z])/g, '$1. $2');
return fixed; }
fixBrokenEquations(content) { let fixed = content;
// Fix mixed equation environments // "\end{equation}$" → "$$" fixed = fixed.replace(/\\end\{equation\}\$/g, '$$'); fixed = fixed.replace(/\$\\begin\{equation\}/g, '$$');
// Fix broken align environments fixed = fixed.replace(/([^$])\s*&=\s*/g, '$1 &= ');
// Fix multiline math that lost structure fixed = fixed.replace(/\$([^$]*?)&=([^$]*?)\$/g, '$$\\begin{align}\n$1 &= $2\n\\end{align}$$');
return fixed; }
fixComplexFigures(content) { let fixed = content;
// Strategy: Convert complex figures to simple markdown BEFORE Pandoc sees them const figurePattern = /\\begin\{figure\*?\}([\s\S]*?)\\end\{figure\*?\}/g; const wrapfigurePattern = /\\begin\{wrapfigure\}(?:\[[^\]]*\])?\{[^}]*\}\{[^}]*\}([\s\S]*?)\\end\{wrapfigure\}/g;
fixed = fixed.replace(figurePattern, (match, figureContent) => { this.stats.figuresProcessed++;
// Extract components safely const imageMatch = figureContent.match(/\\includegraphics(?:\[[^\]]*\])?\{([^}]+)\}/); const captionMatch = figureContent.match(/\\caption\{([\s\S]*?)\}(?=\s*(?:\\label|\\end|\}|$))/); const labelMatch = figureContent.match(/\\label\{([^}]+)\}/);
if (!imageMatch) { return match; // Keep original if we can't parse it }
const imagePath = imageMatch[1].replace(/^figures\//, 'assets/image/'); let caption = captionMatch ? captionMatch[1].trim() : 'Figure'; const label = labelMatch ? labelMatch[1] : '';
// Clean caption thoroughly caption = this.cleanCaption(caption);
// Generate clean markdown const labelAttr = label ? ` {#fig-${label}}` : '';
return `\n\n${labelAttr}\n\n*${caption}*\n\n`; });
// Also handle wrapfigure environments fixed = fixed.replace(wrapfigurePattern, (match, figureContent) => { this.stats.figuresProcessed++;
// Extract components safely const imageMatch = figureContent.match(/\\includegraphics(?:\[[^\]]*\])?\{([^}]+)\}/); const captionMatch = figureContent.match(/\\caption\{([\s\S]*?)\}(?=\s*(?:\\label|\\end|\}|$))/); const labelMatch = figureContent.match(/\\label\{([^}]+)\}/);
if (!imageMatch) { return match; // Keep original if we can't parse it }
const imagePath = imageMatch[1].replace(/^figures\//, 'assets/image/'); let caption = captionMatch ? captionMatch[1].trim() : 'Figure'; const label = labelMatch ? labelMatch[1] : '';
// Clean caption thoroughly caption = this.cleanCaption(caption);
// Generate clean markdown (simpler for wrapfigure) const labelAttr = label ? ` {#fig-${label}}` : '';
return `\n\n${labelAttr}\n\n`; });
return fixed; }
cleanCaption(caption) { let cleaned = caption;
// Handle citations in captions properly cleaned = cleaned.replace(/~\\cite[tp]?\{([^}]+)\}/g, ' [@$1]'); cleaned = cleaned.replace(/\\cite[tp]?\{([^}]+)\}/g, '[@$1]');
// Remove problematic LaTeX commands cleaned = cleaned.replace(/\\textit\{([^}]+)\}/g, '*$1*'); cleaned = cleaned.replace(/\\textbf\{([^}]+)\}/g, '**$1**'); cleaned = cleaned.replace(/\\emph\{([^}]+)\}/g, '*$1*');
// Fix \textsc with complex content cleaned = cleaned.replace(/\\textsc\{([^}]*\([^)]*\)[^}]*)\}/g, '**$1**');
// Handle nested braces safely let depth = 0; let result = ''; for (let i = 0; i < cleaned.length; i++) { const char = cleaned[i]; if (char === '{') { depth++; if (depth === 1) continue; // Skip opening brace } else if (char === '}') { depth--; if (depth === 0) continue; // Skip closing brace } else { result += char; } }
return result.trim(); }
handleProblematicEnvironments(content) { let fixed = content;
// Handle algorithm environments fixed = fixed.replace(/\\begin\{algorithm\}([\s\S]*?)\\end\{algorithm\}/g, (match, algContent) => { return '\n```\nAlgorithm:\n' + algContent.replace(/\\[a-zA-Z]+/g, '') + '\n```\n'; });
// Handle complex math environments fixed = fixed.replace(/\\begin\{align\*?\}([\s\S]*?)\\end\{align\*?\}/g, (match, mathContent) => { const cleaned = mathContent.replace(/\\&/g, '').replace(/\\\\/g, '\n'); return '\n$$\n' + cleaned + '\n$$\n'; });
return fixed; }
phase2_ContentTransformation(content) { let transformed = content;
// Apply command mappings (safer order) transformed = this.applyCommandMappings(transformed);
// Process custom environments transformed = this.processCustomEnvironments(transformed);
// Handle remaining citations transformed = this.processCitations(transformed);
return transformed; }
applyCommandMappings(content) { let processed = content;
// Safe command replacements (most common first) const safeCommands = { 'eg': 'e.g.,', 'ie': 'i.e.,', 'versus': 'vs.', 'wrt': 'w.r.t.', 'etc': 'etc.', 'lerobot': '**LeRobot**', 'lerobotdataset': '`LeRobotDataset`', 'huggingface': '🤗 **Hugging Face**', 'qfunction': 'Q-function', 'qopt': 'Q^*', // Robotics-specific commands from handles.tex 'actionchunk': '\\mathbf{A}', 'actionexpert': '\\mathbf{v}_\\theta', 'pizero': '\\pi_0', 'statespace': '\\mathcal{S}', 'actionspace': '\\mathcal{A}', 'obsspace': '\\mathcal{O}', 'dynamics': '\\mathcal{D}', 'stateplusone': 's_{t+1}', 'state': 's_t', 'action': 'a_t', 'transition': '(s_t, a_t, s_{t+1})', 'sars': '(s_t, a_t, r_t, s_{t+1})', 'transitiongiven': '(s_{t+1} | s_t, a_t)', 'transitionprob': '\\mathbb{P}(s_{t+1} | s_t, a_t)', 'trajectory': '(s_0, a_0, r_0, s_1, a_1, r_1, \\dots, s_{T-1}, a_{T-1}, r_{T-1}, s_T)', 'Jpi': 'J(\\pi_\\theta)', 'supp': '\\text{supp}', 'DKL': '\\text{D}_{\\text{KL}}', 'FK': '\\text{FK}', 'targetvel': '\\dot{p}^*', 'targetpos': 'p^*' };
for (const [command, replacement] of Object.entries(safeCommands)) { const regex = new RegExp(`\\\\${command}(?![a-zA-Z])`, 'g'); const matches = processed.match(regex); if (matches) { this.stats.commandsReplaced += matches.length; processed = processed.replace(regex, replacement); } }
// Math commands (more careful) const mathCommands = ['X', 'Z', 'G', 'D', 'F', 'R', 'S', 'T', 'U', 'Y']; mathCommands.forEach(letter => { const regex = new RegExp(`\\\\${letter}(?![a-zA-Z])`, 'g'); processed = processed.replace(regex, `\\mathcal{${letter}}`); });
// Handle commands with subscripts (like \actionchunk_t) processed = processed.replace(/\\actionchunk_t/g, '\\mathbf{A}_t'); processed = processed.replace(/\\actionexpert_([a-zA-Z0-9]+)/g, '\\mathbf{v}_{\\theta_$1}'); processed = processed.replace(/\\state_([a-zA-Z0-9]+)/g, 's_{$1}'); processed = processed.replace(/\\action_([a-zA-Z0-9]+)/g, 'a_{$1}');
// Fix problematic \textsc commands with complex content processed = processed.replace(/\\textsc\{([^{}]*\([^)]*\)[^{}]*)\}/g, '**$1**'); processed = processed.replace(/\\textsc\{([^}]+)\}/g, '**$1**');
// Fix \url commands to make them MDX-compatible processed = processed.replace(/\\textbf\{\\url\{([^}]+)\}\}/g, '**[$1]($1)**'); processed = processed.replace(/\\url\{([^}]+)\}/g, '[$1]($1)');
return processed; }
processCustomEnvironments(content) { let processed = content;
// TL;DR environment processed = processed.replace( /\\begin\{tldr\}([\s\S]*?)\\end\{tldr\}/g, (match, content) => { this.stats.environmentsProcessed++; return `\n> **TL;DR**\n> ${content.trim()}\n\n`; } );
// Callout environment processed = processed.replace( /\\begin\{callout\}\{([^}]*)\}([\s\S]*?)\\end\{callout\}/g, (match, title, content) => { this.stats.environmentsProcessed++; return `\n> **${title}**\n> ${content.trim()}\n\n`; } );
// Finding command processed = processed.replace( /\\finding\{([^}]*)\}\{([^}]*)\}/g, (match, number, content) => { this.stats.environmentsProcessed++; return `\n> **🔍 Finding ${number}**: ${content}\n\n`; } );
return processed; }
processCitations(content) { let processed = content;
// Handle different citation types processed = processed.replace(/\\citep\{([^}]+)\}/g, '[@$1]'); processed = processed.replace(/\\citet\{([^}]+)\}/g, '@$1'); processed = processed.replace(/\\cite\{([^}]+)\}/g, '[@$1]');
// Handle spaced citations (common issue) processed = processed.replace(/~\\cite/g, ' \\cite'); processed = processed.replace(/~\[@/g, ' [@');
// Count citations const citations = processed.match(/\[@[^\]]+\]/g) || []; this.stats.citationsFixed += citations.length;
return processed; }
phase3_FinalPolish(content) { let polished = content;
// Fix math expressions polished = this.fixMathExpressions(polished);
// Clean up whitespace and structure polished = this.finalCleanup(polished);
return polished; }
fixMathExpressions(content) { let fixed = content;
// Fix common problematic patterns fixed = fixed.replace(/\$\{([^}]+)\}\$/g, '$$$1$$'); // ${...}$ -> $...$ fixed = fixed.replace(/\$([^$]*)\\\$([^$]*)\$/g, '$$$1$2$$'); // $...\$...$ -> $...$
// Fix pi expressions specifically fixed = fixed.replace(/\$\\pi_\$([0-9]+)\$/g, '$\\pi_$1$'); fixed = fixed.replace(/\$\{\\pi_\}([0-9]+)\$/g, '$\\pi_$1$');
// Fix malformed math delimiters fixed = fixed.replace(/\$\$\$+/g, '$$');
this.stats.mathExpressionsFixed++;
return fixed; }
finalCleanup(content) { let cleaned = content;
// Normalize whitespace cleaned = cleaned.replace(/\n{3,}/g, '\n\n'); cleaned = cleaned.replace(/[ \t]+$/gm, ''); // Trailing spaces
// Fix MDX-incompatible angle bracket URLs cleaned = cleaned.replace(/\*\*<(https?:\/\/[^>]+)>\*\*/g, '**[$1]($1)**'); cleaned = cleaned.replace(/<(https?:\/\/[^>]+)>/g, '[$1]($1)');
// Ensure proper spacing around elements cleaned = cleaned.replace(/\n\n\n+/g, '\n\n');
return cleaned.trim(); }
getStats() { return this.stats; }
setDebugMode(enabled) { this.debugMode = enabled; }}123456---title: "Bringing paper to life:\n A modern template for\n scientific writing"subtitle: "Publish‑ready workflow that lets you focus on ideas, not infrastructure"description: "Publish‑ready workflow that lets you focus on ideas, not infrastructure"authors:12345---title: "Bringing paper to life:\n A modern template for\n scientific writing"subtitle: "Publish‑ready workflow that lets you focus on ideas, not infrastructure"description: "Publish‑ready workflow that lets you focus on ideas, not infrastructure"authors:
1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/bin/bash
# 🚀 Script de setup pour collaboration GitHub Codespaces# Usage: ./scripts/setup-collaboration.sh
echo "🔧 Configuration de l'environnement collaboratif..."
# Aller dans le dossier appcd app
# Installer les dépendances si pas déjà faitif [ ! -d "node_modules" ]; then echo "📦 Installation des dépendances..." npm installfi
# Démarrer le serveur de développement en arrière-planecho "🌟 Démarrage du serveur Astro..."npm run dev -- --host 0.0.0.0 --port 3000 &DEV_PID=$!
# Attendre que le serveur démarresleep 5
echo "✅ Configuration terminée !"echo ""echo "🎯 URLs disponibles :"echo " • Développement: http://localhost:3000"echo " • Preview: http://localhost:8080"echo ""echo "👥 Pour collaborer :"echo " 1. Ouvrez la palette de commandes (Ctrl+Shift+P)"echo " 2. Tapez 'Live Share: Start Collaborative Session'"echo " 3. Partagez le lien généré avec vos collaborateurs"echo ""echo "📝 Fichiers principaux à éditer :"echo " • src/content/article.mdx"echo " • src/content/chapters/*.mdx"echo " • src/content/bibliography.bib"echo ""echo "🔄 Le serveur se recharge automatiquement à chaque modification !"
# Garder le script en vie pour maintenir le serveurwait $DEV_PID.gitignore+2
COLLABORATION.mdDeleted-130
README.md+1-41
app/.astro/astro/content.d.ts+24-36
app/package.json
app/scripts/export-latex.mjs+40-40
app/scripts/latex-converter/README.mdAdded+107
app/scripts/latex-converter/bibliography-cleaner.mjsAdded+123
app/scripts/latex-converter/config.mjsAdded+59
app/scripts/latex-converter/converter.mjsAdded+456
app/scripts/latex-converter/image-transformer.mjsAdded+179
app/scripts/latex-converter/index.mjsAdded+75
app/scripts/latex-converter/preprocessor.mjsAdded+115
app/scripts/latex-converter/robust-preprocessor.mjsAdded+399
app/src/content/article.mdx+1-2
scripts/setup-collaboration.shDeleted-44