Skip to content

Commit

Permalink
Tweak footer e layout categorie, fix metapagine, aggiornamento tradut…
Browse files Browse the repository at this point in the history
…tore
  • Loading branch information
octospacc committed Sep 21, 2024
1 parent c1bac2d commit 7ab6681
Show file tree
Hide file tree
Showing 11 changed files with 198 additions and 133 deletions.
70 changes: 58 additions & 12 deletions Scripts/Translate/Main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
#!/usr/bin/env python3
ModificationMetadataKey = "lastmod"
KeepOriginalMetadata = ["draft", "date", "lastmod"]
DestinationLanguages = ["it", "en", "es", "fr"] # "de", "eo"
IncludePaths = ["/"]
ExcludePaths = ["/categories", "/note/2024-09-19-Raspberry-Output-Audio-Both.md", "/miscellanea/Devlogs.md"] # "/miscellanea/PicoBlog.md"
ExcludePaths = ["/note/2024-09-19-Raspberry-Output-Audio-Both.md", "/miscellanea/Devlogs.md"] # "/miscellanea/PicoBlog.md"

import subprocess
from os import getcwd, listdir
from os.path import dirname, realpath, isfile, isdir
from pathlib import Path
from translate_shell.translate import translate

# TODO somehow handle overriding frontmatter data for some translation (title, slug, ...)
# TODO somehow handle overriding frontmatter data for some translation (title, slug, ...) (via in other files or commented metadata lines?)
# TODO handle deleted files? (it should probably be done in another sh script, not here)

def printf(*objects):
Expand All @@ -26,11 +28,11 @@ def make_destination_path(document_path, destination_language):
+ '/'.join(document_path.split('/')[1:]))

def is_translation_uptodate(source_path, destination_path):
original_lines = split_text_with_frontmatter(read_original_document(source_path))[1].splitlines()
translated_lines = split_text_with_frontmatter(open(destination_path, 'r').read())[1].splitlines()
original_lines = split_with_frontmatter(read_original_document(source_path))[1].splitlines()
translated_lines = split_with_frontmatter(open(destination_path, 'r').read())[1].splitlines()
for [index, original_line] in enumerate(original_lines):
line_key = original_line.split('=')[0]
if line_key.strip().lower() == "lastmod":
if line_key.strip().lower() == ModificationMetadataKey:
if original_line != translated_lines[index]:
return False
break
Expand All @@ -40,7 +42,7 @@ def is_translation_uptodate(source_path, destination_path):
def needs_translation(source_path, destination_language=None):
for exclude_path in ExcludePaths:
document_path = ('/' + '/'.join(source_path.split('/')[1:]))
if (document_path == exclude_path) or document_path.startswith(exclude_path + '/'):
if (document_path == exclude_path) or document_path.startswith(exclude_path.rstrip('/') + '/'):
return False
if not read_original_document(source_path).strip():
return False
Expand All @@ -63,7 +65,7 @@ def find_documents(folder_path):
documents[document].append(destination_language)
return documents

def split_text_with_frontmatter(document_text):
def split_with_frontmatter(document_text):
text_header = document_text.strip().splitlines()[0].strip()
if text_header in ["---", "+++"]:
text_tokens = document_text.split(text_header)
Expand All @@ -76,7 +78,7 @@ def fix_frontmatter(translated_text, reference_text):
if translated_line.strip() and (translated_line.lstrip() == translated_line):
reference_line = reference_lines[index]
line_key = reference_line.split('=')[0]
if line_key.strip().lower() in ["draft", "date", "lastmod"]:
if line_key.strip().lower() in KeepOriginalMetadata:
translated_line = reference_line
else:
line_value = '='.join(translated_line.split('=')[1:])
Expand All @@ -86,11 +88,50 @@ def fix_frontmatter(translated_text, reference_text):
result += (translated_line + '\n')
return result

# <https://stackoverflow.com/a/18815890>
def ascii_to_number(text:str) -> int:
return int(''.join(format(ord(i), 'b').zfill(8) for i in text), 2)

# <https://stackoverflow.com/a/699891>, <https://stackoverflow.com/a/40559005>
def number_to_ascii(number:int) -> str:
binary = format(int(number), '016b')
binary = binary.zfill(len(binary) + (8 - (len(binary) % 8)))
return ''.join(chr(int(binary[(i * 8):((i * 8) + 8)], 2)) for i in range(len(binary) // 8))

# TODO add checks for number-strings to ensure they aren't already in the literal text
# TODO handle code blocks and .notranslate HTML elements
# TODO fix strange bugs
def wrap_for_translation(original_text):
#return original_text
original_text = (original_text
.replace("{{%", "{{@%").replace("%}}", "%@}}")
.replace("{{<", "{{@<").replace(">}}", ">@}}"))
original_tokens = original_text.split("{{@")
#[(("{{@" if i else '') + c) for [i, c] in enumerate(original_text.split("{{@"))]
for i in range(1, len(original_tokens)):
token_tokens = original_tokens[i].split("@}}")
token_tokens[0] = (f"{TranslationMagic}__" + str(ascii_to_number("{{@" + token_tokens[0] + "@}}")) + "__").replace("9", "9_")
original_tokens[i] = ''.join(token_tokens)
#print(unwrap_from_translation(''.join(original_tokens)))
#exit(1)
return ''.join(original_tokens)

def unwrap_from_translation(translated_text):
#return translated_text
translated_tokens = translated_text.split(f"{TranslationMagic}__")
for i in range(1, len(translated_tokens)):
token_tokens = translated_tokens[i].split("__")
token_tokens[0] = number_to_ascii(token_tokens[0].replace(' ', '').replace('_', ''))
translated_tokens[i] = (token_tokens[0] + "__".join(token_tokens[1:]))
return (''.join(translated_tokens)
.replace("{{@%", "{{%").replace("%@}}", "%}}")
.replace("{{@<", "{{<").replace(">@}}", ">}}"))

def translate_document(document_path, documents):
printf(f"* {document_path} ->")
for destination_language in documents[document_path]:
source_language = get_source_language(document_path)
original_text = read_original_document(document_path)
original_text = wrap_for_translation(read_original_document(document_path))
printf('', destination_language)
try:
is_python_translator = True
Expand All @@ -101,10 +142,13 @@ def translate_document(document_path, documents):
printf('❌', exception)
try:
is_python_translator = False
temporary_path = ("./tmp/" + document_path)
Path('/'.join(temporary_path.split('/')[:-1])).mkdir(parents=True, exist_ok=True)
open(temporary_path, 'w').write(original_text)
translated = subprocess.run(
("bash", "../Scripts/Lib/translate-shell.bash", "-brief", "-no-autocorrect",
"-t", destination_language, "-s", source_language,
("file://" + "../content/" + document_path)),
("file://" + temporary_path)),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if translated.stderr:
Expand All @@ -116,7 +160,7 @@ def translate_document(document_path, documents):
translated_text = (translated.results[0].paraphrase
if is_python_translator else translated.stdout.decode())
translated_preamble = ("\n\n{{< noticeAutomaticTranslation " + source_language + " >}}\n\n")
if (translated_tokens := split_text_with_frontmatter(translated_text)):
if (translated_tokens := split_with_frontmatter(translated_text)):
translated_tokens[1] = fix_frontmatter(translated_tokens[1], original_text.split(translated_tokens[0])[1])
if translated_tokens[3].strip():
translated_tokens.insert(3, translated_preamble)
Expand All @@ -125,7 +169,7 @@ def translate_document(document_path, documents):
translated_text = (translated_preamble + translated_text)
destination_path = make_destination_path(document_path, destination_language)
Path('/'.join(destination_path.split('/')[:-1])).mkdir(parents=True, exist_ok=True)
open(destination_path, 'w').write(translated_text)
open(destination_path, 'w').write(unwrap_from_translation(translated_text))
printf('\n')

def main():
Expand All @@ -139,6 +183,8 @@ def main():
def read_from_scripts(relative_path:str):
return open((dirname(realpath(__file__)) + '/../' + relative_path), 'r').read()

TranslationMagic = ("__" + str(ascii_to_number("sitoctt")))

if __name__ == "__main__":
globals_text = read_from_scripts('Lib/Globals.sh')
exec(globals_text.split('#' + globals_text.splitlines()[0].split('#!')[1] + '!')[0])
Expand Down
6 changes: 6 additions & 0 deletions assets/ButtonBadges.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ file = "Follow-me-on-mastodon.png"
href = "https://mastodon.uno/@octo"
rel = "me"

[[20-me]]
alt = "Visita la OctoSpacc Hub"
file = "Sites/octospacc-hub-1.png"
href = "https://hub.octt.eu.org"
rel = "me"

[[20-me]]
alt = "Visita il mio Fritto Misto di OctoSpacc"
file = "Sites/fritto-misto-di-octospacc-1.png"
Expand Down
26 changes: 4 additions & 22 deletions content/it/_index.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,16 @@
+++
Title = "il ✨sitoctt✨ — Home"
Description = "Octt sono io... e questo è letteralmente il mio sito (uwu)."
Lastmod = 2024-08-27
Lastmod = 2024-09-21
+++

Una volta qui era tutta campagn— ehm, volevo dire... era tutta una lista di parole ammassate alla male e peggio. Non solo non piaceva più nemmeno a me, ma non è proprio buona creanza nell'anno del Signore 2024 (e oltre), quindi...

Ora c'è questa lista di tutti i miei ultimissimi articoli, e pagine sfuse che ho aggiornato di recente, mentre la vecchia home è a ["Sul sitoctt"]({{< relref "/miscellanea/Sul-sitoctt/" >}}) finché non avrò riorganizzato tutto. Benvenut<code class="notranslate" data-lang="it"><!--
--><span class="BlinkA">a</span><!--
--><span class="dn">/</span><!--
--><span class="Blink_">/</span><!--
--><span class="BlinkO">o</span></code> nel ✨sitoctt✨!

(Lavori in corso per ancora qualche giorno, quindi forse link rotti e pagine sformate, mi dispiace!!!)
<!-- (Lavori in corso per ancora qualche giorno, quindi forse link rotti e pagine sformate, mi dispiace!!!) -->

<style>
/* Animazioni per le desinenze */
.BlinkA {
Animation: BlinkerA 0.25s Step-Start Infinite;
}
@Keyframes BlinkerA {
0% {Position: Absolute; Visibility: Hidden;}
50% {Position: Static; Visibility: Visible;}
100% {Position: Absolute; Visibility: Hidden;}
}
.BlinkO {
Animation: BlinkerO 0.25s Step-Start Infinite;
}
@Keyframes BlinkerO {
0% {Position: Static; Visibility: Visible;}
50% {Position: Absolute; Visibility: Hidden;}
100% {Position: Static; Visibility: Visible;}
}
</style>
<link rel="stylesheet" href="/desinenze-blink.css"/>
2 changes: 1 addition & 1 deletion content/it/blog/_index.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
+++
Title = "Blog"
Title = "Blog📚️"
Aliases = [
"/Posts/index.html",
"/Categories/Blog.html",
Expand Down
4 changes: 2 additions & 2 deletions content/it/categories/MicroBlog/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
Title = "📒 Vecchi MicroBlog"
#Index = True
#URLs = MicroBlog.html Diarylog.html
Categories = [ "Blog" ]
#Categories = [ "Blog" ]
+++

Come annunciato nell'articolo "[🎇 Il resocontoctt di questo 2023, almeno in termini di posting!](../Posts/2023-12-31-Resocontoctt-2023.html#-Il-MicroBlog-nuovissimo-alla-fa)", il Vecchio MicroBlog è ora deprecato, e non verrà più aggiornato. Quello che segue è l'archivio dei vecchi contenuti, che rimarrà leggibile. I nuovi post verranno quindi pubblicati sul Nuovo MicroBlog unificato, raggiungibile dal menu del sito.
Come annunciato nell'articolo "[🎇 Il resocontoctt di questo 2023, almeno in termini di posting!]({{< relref "/blog/2023-12-31-Resocontoctt-2023/#il-microblog-nuovissimo-alla-faccia-du-rove" >}})", il Vecchio MicroBlog è ora deprecato, e non verrà più aggiornato. Quello che segue è l'archivio dei vecchi contenuti, che rimarrà leggibile. I nuovi post verranno quindi pubblicati sul Nuovo MicroBlog unificato, raggiungibile dal menu del sito.

_Nota: I contenuti negli archivi possono aver subito redazioni non segnalate._
Loading

0 comments on commit 7ab6681

Please sign in to comment.