Download server/word.js from SSSAssist/Thoth: direct link, hf CLI and curl.
- Browser
- Download file 17 kB
-
https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/server/word.js
- Command line
-
hf download hf://spaces/SSSAssist/Thoth/server/word.js
-
curl -L -o word.js https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/server/word.js
17 kB
| // Word (.docx) çıktısını APA 7 biçimine getiren yardımcılar: | |
| // - Pandoc'un varsayılan şablon belgesinden APA 7 stilleriyle bir şablon (reference.docx) üretir. | |
| // - apa7 sınıfının başlık sayfası alanlarını kaynaktan çıkarır. | |
| // - Pandoc ara biçimine (JSON) APA başlık sayfası, özet, tablo/şekil başlıkları ve kaynakça bölümü ekler. | |
| import { existsSync } from 'node:fs'; | |
| import { writeFile } from 'node:fs/promises'; | |
| import path from 'node:path'; | |
| import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate'; | |
| import { DATA_DIR } from './config.js'; | |
| const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'; | |
| const FONT = 'Times New Roman'; | |
| const RFONTS = `<w:rFonts w:ascii="${FONT}" w:hAnsi="${FONT}" w:eastAsia="${FONT}" w:cs="${FONT}"/>`; | |
| // APA 7: çift satır aralığı, paragraflar arasında boşluk yok, ilk satır girintisi 1,27 cm (0,5 inç). | |
| const SPACING = '<w:spacing w:before="0" w:after="0" w:line="480" w:lineRule="auto"/>'; | |
| const INDENT = '<w:ind w:firstLine="720"/>'; | |
| const BLACK = '<w:color w:val="000000"/><w:sz w:val="24"/><w:szCs w:val="24"/>'; | |
| /** OOXML öğe sırasına uygun paragraf stili. */ | |
| function paragraphStyle(id, name, { keep = false, indent = '', center = false, right = false, outline, bold = false, italic = false, basedOn = 'Normal' } = {}) { | |
| const pPr = [ | |
| keep ? '<w:keepNext/><w:keepLines/>' : '', | |
| SPACING, | |
| indent, | |
| center ? '<w:jc w:val="center"/>' : right ? '<w:jc w:val="right"/>' : '', | |
| outline != null ? `<w:outlineLvl w:val="${outline}"/>` : '', | |
| ].join(''); | |
| const rPr = [RFONTS, bold ? '<w:b/><w:bCs/>' : '', italic ? '<w:i/><w:iCs/>' : '', BLACK].join(''); | |
| return `<w:style w:type="paragraph" w:styleId="${id}"><w:name w:val="${name}"/><w:basedOn w:val="${basedOn}"/><w:qFormat/><w:pPr>${pPr}</w:pPr><w:rPr>${rPr}</w:rPr></w:style>`; | |
| } | |
| const APA_STYLES = [ | |
| paragraphStyle('BodyText', 'Body Text', { indent: INDENT }), | |
| paragraphStyle('FirstParagraph', 'First Paragraph', { indent: INDENT, basedOn: 'BodyText' }), | |
| paragraphStyle('Compact', 'Compact'), | |
| paragraphStyle('Title', 'Title', { keep: true, center: true, bold: true }), | |
| paragraphStyle('Subtitle', 'Subtitle', { center: true }), | |
| paragraphStyle('Author', 'Author', { center: true }), | |
| paragraphStyle('Date', 'Date', { center: true }), | |
| paragraphStyle('AbstractTitle', 'Abstract Title', { keep: true, center: true, bold: true }), | |
| paragraphStyle('Abstract', 'Abstract'), | |
| // APA 7 başlık düzeyleri | |
| paragraphStyle('Heading1', 'heading 1', { keep: true, center: true, outline: 0, bold: true }), | |
| paragraphStyle('Heading2', 'heading 2', { keep: true, outline: 1, bold: true }), | |
| paragraphStyle('Heading3', 'heading 3', { keep: true, outline: 2, bold: true, italic: true }), | |
| paragraphStyle('Heading4', 'heading 4', { keep: true, indent: INDENT, outline: 3, bold: true }), | |
| paragraphStyle('Heading5', 'heading 5', { keep: true, indent: INDENT, outline: 4, bold: true, italic: true }), | |
| // Kaynakça: asılı girinti | |
| paragraphStyle('Bibliography', 'Bibliography', { indent: '<w:ind w:left="720" w:hanging="720"/>' }), | |
| paragraphStyle('BlockText', 'Block Text', { indent: '<w:ind w:left="720"/>' }), | |
| paragraphStyle('Caption', 'Caption', { keep: true }), | |
| paragraphStyle('TableCaption', 'Table Caption', { keep: true, basedOn: 'Caption' }), | |
| paragraphStyle('ImageCaption', 'Image Caption', { basedOn: 'Caption' }), | |
| paragraphStyle('TOCHeading', 'TOC Heading', { keep: true, center: true, bold: true }), | |
| paragraphStyle('Header', 'header', { right: true }), | |
| // Thoth'un eklediği paragraflar için (Pandoc "custom-style" ile adından eşler) | |
| paragraphStyle('APAEtiket', 'APA Etiket', { keep: true }), | |
| paragraphStyle('APAOrtali', 'APA Ortalı', { center: true }), | |
| paragraphStyle('APADenklemNo', 'APA Denklem No', { right: true }), | |
| `<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:basedOn w:val="BodyTextChar"/><w:rPr><w:color w:val="000000"/><w:u w:val="none"/></w:rPr></w:style>`, | |
| ]; | |
| const HEADER_XML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?> | |
| <w:hdr xmlns:w="${W}"><w:p><w:pPr><w:pStyle w:val="Header"/><w:jc w:val="right"/></w:pPr><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p></w:hdr>`; | |
| // A4, dört kenarda 2,54 cm (1 inç) boşluk, sağ üstte sayfa numarası. | |
| const SECT_PR = '<w:sectPr><w:headerReference w:type="default" r:id="rIdThothHeader"/><w:footnotePr><w:numRestart w:val="eachSect"/></w:footnotePr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>'; | |
| /** Pandoc'un varsayılan şablon belgesini APA 7 stillerine çevirir. */ | |
| export function patchReferenceDoc(bytes) { | |
| const zip = unzipSync(bytes); | |
| let styles = strFromU8(zip['word/styles.xml']); | |
| styles = styles | |
| .replace(/<w:rPrDefault>[\s\S]*?<\/w:rPrDefault>/, `<w:rPrDefault><w:rPr>${RFONTS}${BLACK}<w:lang w:val="tr-TR" w:eastAsia="en-US" w:bidi="ar-SA"/></w:rPr></w:rPrDefault>`) | |
| .replace(/<w:pPrDefault>[\s\S]*?<\/w:pPrDefault>/, `<w:pPrDefault><w:pPr>${SPACING}</w:pPr></w:pPrDefault>`) | |
| // Tema yazı tipleri ve renkler: her yerde Times New Roman ve siyah | |
| .replace(/<w:rFonts\b[^>]*?[Tt]heme[^>]*\/>/g, RFONTS) | |
| .replace(/<w:color\b[^>]*\/>/g, '<w:color w:val="000000"/>') | |
| .replace(/<w:sz w:val="\d+"\s*\/>/g, '<w:sz w:val="24"/>') | |
| .replace(/<w:szCs w:val="\d+"\s*\/>/g, '<w:szCs w:val="24"/>'); | |
| for (const style of APA_STYLES) { | |
| const id = style.match(/w:styleId="([^"]+)"/)[1]; | |
| const existing = new RegExp(`<w:style\\b[^>]*w:styleId="${id}"[^>]*>[\\s\\S]*?</w:style>`); | |
| styles = existing.test(styles) ? styles.replace(existing, style) : styles.replace('</w:styles>', `${style}</w:styles>`); | |
| } | |
| zip['word/styles.xml'] = strToU8(styles); | |
| const doc = strFromU8(zip['word/document.xml']); | |
| zip['word/document.xml'] = strToU8(doc.replace(/<w:sectPr>[\s\S]*?<\/w:sectPr>/, SECT_PR)); | |
| zip['word/header1.xml'] = strToU8(HEADER_XML); | |
| const rels = strFromU8(zip['word/_rels/document.xml.rels']); | |
| zip['word/_rels/document.xml.rels'] = strToU8(rels.replace( | |
| '</Relationships>', | |
| '<Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Id="rIdThothHeader" Target="header1.xml" /></Relationships>', | |
| )); | |
| const types = strFromU8(zip['[Content_Types].xml']); | |
| zip['[Content_Types].xml'] = strToU8(types.replace( | |
| '</Types>', | |
| '<Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml" /></Types>', | |
| )); | |
| return zipSync(zip); | |
| } | |
| const escapeXml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); | |
| /** Şablon belgenin üst bilgisine solda kısa başlığı (APA 7 profesyonel makale), sağda sayfa numarasını koyar. */ | |
| export function withRunningHead(referenceBytes, runningHead) { | |
| const zip = unzipSync(new Uint8Array(referenceBytes)); | |
| // A4 metin genişliği: 11906 - 2 x 1440 = 9026 twip | |
| zip['word/header1.xml'] = strToU8(HEADER_XML.replace( | |
| '<w:pPr><w:pStyle w:val="Header"/><w:jc w:val="right"/></w:pPr>', | |
| `<w:pPr><w:pStyle w:val="Header"/><w:tabs><w:tab w:val="right" w:pos="9026"/></w:tabs><w:jc w:val="left"/></w:pPr><w:r><w:t xml:space="preserve">${escapeXml(runningHead)}</w:t></w:r><w:r><w:tab/></w:r>`, | |
| )); | |
| return zipSync(zip); | |
| } | |
| const REFERENCE_DOC = path.join(DATA_DIR, 'apa7-sablon-v1.docx'); | |
| /** APA 7 şablon belgesinin yolunu verir; yoksa Pandoc'un varsayılanından üretir. */ | |
| export async function apaReferenceDoc(runPandoc) { | |
| if (existsSync(REFERENCE_DOC)) return REFERENCE_DOC; | |
| const { code, stdout, stderr } = await runPandoc(['--print-default-data-file', 'reference.docx']); | |
| if (code !== 0) throw new Error(`Word şablonu alınamadı: ${stderr}`); | |
| await writeFile(REFERENCE_DOC, patchReferenceDoc(new Uint8Array(stdout))); | |
| return REFERENCE_DOC; | |
| } | |
| // ---- apa7 sınıfının başlık sayfası alanları ---- | |
| /** `\komut{...}` biçimindeki ilk komutun (yıldızsız) dengeli parantezli bağımsız değişkenini döndürür. */ | |
| export function extractCommand(source, name) { | |
| const re = new RegExp(`\\\\${name}(?![a-zA-Z*])\\s*\\{`, 'g'); | |
| for (const m of source.matchAll(re)) { | |
| // Yorum satırındaki komutlar atlanır. | |
| const lineStart = source.lastIndexOf('\n', m.index) + 1; | |
| if (/(?<!\\)%/.test(source.slice(lineStart, m.index))) continue; | |
| let depth = 1; | |
| let i = m.index + m[0].length; | |
| const start = i; | |
| for (; i < source.length && depth > 0; i++) { | |
| if (source[i] === '\\') i++; | |
| else if (source[i] === '{') depth++; | |
| else if (source[i] === '}') depth--; | |
| } | |
| if (depth === 0) return source.slice(start, i - 1).trim(); | |
| } | |
| return null; | |
| } | |
| export const FRONT_FIELDS = ['title', 'shorttitle', 'authorsnames','authorsaffiliations', 'course', 'professor', 'duedate', 'authornote', 'abstract', 'keywords']; | |
| /** Belge apa7 sınıfını kullanıyorsa kipini ve başlık sayfası alanlarını (LaTeX olarak) verir. */ | |
| export function apaFrontMatter(source) { | |
| const cls = source.match(/\\documentclass\s*(?:\[([^\]]*)\])?\s*\{apa7\}/); | |
| if (!cls) return null; | |
| const options = (cls[1] ?? '').split(',').map((o) => o.trim()); | |
| const fields = {}; | |
| for (const f of FRONT_FIELDS) fields[f] = extractCommand(source, f); | |
| return { | |
| student: options.includes('stu'), | |
| repeatTitle: !options.includes('donotrepeattitle'), | |
| fields, | |
| }; | |
| } | |
| // ---- Pandoc ara biçimi (JSON) yardımcıları ---- | |
| const str = (text) => text.split(/(\s+)/).filter(Boolean).map((p) => (/^\s+$/.test(p) ? { t: 'Space' } : { t: 'Str', c: p })); | |
| const para = (inlines) => ({ t: 'Para', c: inlines }); | |
| const styled = (style, blocks) => ({ t: 'Div', c: [['', [], [['custom-style', style]]], blocks] }); | |
| const raw = (xml) => ({ t: 'RawBlock', c: ['openxml', xml] }); | |
| export const PAGE_BREAK = raw('<w:p><w:r><w:br w:type="page"/></w:r></w:p>'); | |
| const EMPTY_LINE = raw('<w:p/>'); | |
| export const TOC = raw( | |
| '<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Table of Contents"/><w:docPartUnique/></w:docPartObj></w:sdtPr><w:sdtContent>' + | |
| '<w:p><w:pPr><w:pStyle w:val="TOCHeading"/></w:pPr><w:r><w:t>İçindekiler</w:t></w:r></w:p>' + | |
| '<w:p><w:r><w:fldChar w:fldCharType="begin" w:dirty="true"/></w:r><w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" \\h \\z \\u </w:instrText></w:r>' + | |
| '<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>İçindekiler tablosunu görmek için alanları güncelleyin (F9).</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>' + | |
| '</w:sdtContent></w:sdt>', | |
| ); | |
| /** Bir blok listesinin ilk paragrafının satır içi öğeleri. */ | |
| const inlinesOf = (blocks) => { | |
| const first = (blocks ?? []).find((b) => b.t === 'Plain' || b.t === 'Para'); | |
| return first ? first.c : []; | |
| }; | |
| /** Satır içi öğelerin düz metni. */ | |
| export function plainText(blocks) { | |
| const text = (node) => { | |
| if (Array.isArray(node)) return node.map(text).join(''); | |
| if (!node || typeof node !== 'object') return ''; | |
| if (node.t === 'Str') return node.c; | |
| if (node.t === 'Space' || node.t === 'SoftBreak' || node.t === 'LineBreak') return ' '; | |
| return Array.isArray(node.c) ? text(node.c) : ''; | |
| }; | |
| return text(inlinesOf(blocks)).trim(); | |
| } | |
| /** | |
| * Etiketli ayrık denklemlere APA'daki gibi sağda "(1)" numarası verir ve \ref atıflarını bu numaralarla | |
| * değiştirir (Pandoc denklem atıflarını "[eq:etiket]" olarak bırakır). | |
| */ | |
| function numberEquations(blocks) { | |
| const numbers = new Map(); | |
| const collect = (node) => { | |
| if (Array.isArray(node)) return node.forEach(collect); | |
| if (!node || typeof node !== 'object') return; | |
| if (node.t === 'Math' && node.c[0].t === 'DisplayMath') { | |
| for (const m of node.c[1].matchAll(/\\label\{([^}]+)\}/g)) if (!numbers.has(m[1])) numbers.set(m[1], numbers.size + 1); | |
| } | |
| Object.values(node).forEach(collect); | |
| }; | |
| collect(blocks); | |
| if (!numbers.size) return blocks; | |
| const labelsIn = (node) => JSON.stringify(node).match(/\\\\label\{[^}]+\}/g)?.map((l) => l.slice(8, -1)) ?? []; | |
| const rewrite = (node) => { | |
| if (Array.isArray(node)) { | |
| // Denklem içeren paragrafın ardına sağa yaslı "(n)" satırı eklenir. | |
| return node.flatMap((n) => { | |
| if ((n?.t === 'Para' || n?.t === 'Plain') && n.c.some((i) => i.t === 'Math' && i.c[0].t === 'DisplayMath')) { | |
| const nums = labelsIn(n).filter((l) => numbers.has(l)).map((l) => numbers.get(l)); | |
| return [rewrite(n), ...nums.map((num) => styled('APA Denklem No', [para([{ t: 'Str', c: `(${num})` }])]))]; | |
| } | |
| return [rewrite(n)]; | |
| }); | |
| } | |
| if (!node || typeof node !== 'object') return node; | |
| if (node.t === 'Math' && node.c[0].t === 'DisplayMath') return { t: 'Math', c: [node.c[0], node.c[1].replace(/\\label\{[^}]*\}/g, '')] }; | |
| if (node.t === 'Link') { | |
| const target = node.c[2][0].replace(/^#/, ''); | |
| if (numbers.has(target)) return { t: 'Str', c: String(numbers.get(target)) }; | |
| } | |
| const copy = {}; | |
| for (const [k, v] of Object.entries(node)) copy[k] = rewrite(v); | |
| return copy; | |
| }; | |
| return rewrite(blocks); | |
| } | |
| function containsCite(node) { | |
| if (Array.isArray(node)) return node.some(containsCite); | |
| if (!node || typeof node !== 'object') return false; | |
| if (node.t === 'Cite') return true; | |
| return Object.values(node).some(containsCite); | |
| } | |
| /** | |
| * APA 7 düzenlemeleri: | |
| * - Tablo ve şekiller: üstte kalın "Tablo 1" / "Şekil 1", altında italik başlık. | |
| * - apa7 belgelerinde başlık sayfası, özet sayfası ve metnin başında yinelenen başlık. | |
| * - Atıf varsa yeni sayfada "Kaynaklar" bölümü. | |
| * @param front apaFrontMatter() sonucu; alanlar Pandoc blok listesine çevrilmiş olarak (fieldBlocks) | |
| */ | |
| export function applyApa(ast, { front = null, fieldBlocks = {}, hasBibliography = false } = {}) { | |
| let tables = 0; | |
| let figures = 0; | |
| const label = (word, n, captionInlines) => [ | |
| styled('APA Etiket', [para([{ t: 'Strong', c: [...str(word), { t: 'Space' }, { t: 'Str', c: String(n) }] }])]), | |
| styled('APA Etiket', [para([{ t: 'Emph', c: captionInlines }])]), | |
| ]; | |
| const mapBlocks = (blocks) => blocks.flatMap((b) => { | |
| if (b.t === 'Table') { | |
| const caption = inlinesOf(b.c[1][1]); | |
| if (!caption.length) return [b]; | |
| tables += 1; | |
| const table = { ...b, c: [b.c[0], [null, []], ...b.c.slice(2)] }; | |
| return [...label('Tablo', tables, caption), table]; | |
| } | |
| if (b.t === 'Figure') { | |
| const caption = inlinesOf(b.c[1][1]); | |
| figures += 1; | |
| return [...(caption.length ? label('Şekil', figures, caption) : []), ...mapBlocks(b.c[2])]; | |
| } | |
| if (b.t === 'Div') return [{ ...b, c: [b.c[0], mapBlocks(b.c[1])] }]; | |
| if (b.t === 'BlockQuote') return [{ ...b, c: mapBlocks(b.c) }]; | |
| return [b]; | |
| }); | |
| let blocks = mapBlocks(numberEquations(ast.blocks)); | |
| if (front) { | |
| const f = fieldBlocks; | |
| const line = (key, wrap = (x) => x) => (inlinesOf(f[key]).length ? [styled('APA Ortalı', [para(wrap(inlinesOf(f[key])))])] : []); | |
| const strong = (inl) => [{ t: 'Strong', c: inl }]; | |
| const titlePage = [ | |
| EMPTY_LINE, EMPTY_LINE, EMPTY_LINE, | |
| ...line('title', strong), | |
| EMPTY_LINE, | |
| ...line('authorsnames'), | |
| ...line('authorsaffiliations'), | |
| ...(front.student ? [...line('course'), ...line('professor'), ...line('duedate')] : []), | |
| ]; | |
| if (!front.student && f.authornote?.length) { | |
| titlePage.push(EMPTY_LINE, EMPTY_LINE, styled('APA Ortalı', [para(strong(str('Yazar Notu')))]), ...f.authornote); | |
| } | |
| const abstractPage = f.abstract?.length | |
| ? [ | |
| PAGE_BREAK, | |
| styled('APA Ortalı', [para(strong(str('Özet')))]), | |
| styled('Abstract', f.abstract), | |
| ...(inlinesOf(f.keywords).length | |
| ? [styled('Body Text', [para([{ t: 'Emph', c: str('Anahtar kelimeler:') }, { t: 'Space' }, ...inlinesOf(f.keywords)])])] | |
| : []), | |
| ] | |
| : []; | |
| const repeated = front.repeatTitle ? line('title', strong) : []; | |
| blocks = [...titlePage, ...abstractPage, PAGE_BREAK, ...repeated, ...blocks]; | |
| ast.meta = {}; // başlık bilgileri gövdeye yazıldı; Pandoc'un başlık bloğu kullanılmaz | |
| } | |
| if (hasBibliography && containsCite(blocks)) { | |
| blocks.push( | |
| PAGE_BREAK, | |
| { t: 'Header', c: [1, ['kaynaklar', ['unnumbered'], []], str('Kaynaklar')] }, | |
| { t: 'Div', c: [['refs', [], []], []] }, | |
| ); | |
| } | |
| // Ardışık sayfa sonları (ör. kaynakçadan önce \clearpage) boş sayfa oluşturmasın. | |
| const isEmpty = (b) => b.t === 'Div' && !b.c[1].length && !b.c[0][0]; | |
| blocks = blocks.filter((b) => !isEmpty(b)); | |
| blocks = blocks.filter((b, i) => !(b === PAGE_BREAK && (i === 0 || blocks[i - 1] === PAGE_BREAK))); | |
| return { ...ast, blocks }; | |
| } | |