mirror of
https://forge.chapril.org/tykayn/orgmode-to-gemini-blog
synced 2025-06-20 09:04:42 +02:00
up gen gemini
This commit is contained in:
parent
bba1df0377
commit
6134f677fa
622 changed files with 165 additions and 544 deletions
|
@ -23,7 +23,7 @@ generate_linkings_json = True
|
|||
# Configurer argparse pour prendre le blog en argument
|
||||
parser = argparse.ArgumentParser(description='Générer une liste des derniers articles de blog.')
|
||||
parser.add_argument('blog', type=str, help='Nom du dossier du blog à traiter', default='cipherbliss_blog')
|
||||
parser.add_argument('--run_gemini', type=str, help='Activer ou non la génération des billets gemini', default=False)
|
||||
parser.add_argument('--run_gemini', type=str, help='Activer ou non la génération des billets gemini', default=True)
|
||||
parser.add_argument('--run_pandoc', type=str, help='Activer ou non la génération des fichiers html', default=True)
|
||||
parser.add_argument('--enable_roam_id_rewrite', type=str, help='Activer ou non la réécriture des liens roam', default=False)
|
||||
parser.add_argument('--force_html_regen', action='store_true', help='Forcer la régénération des fichiers HTML même s\'ils existent déjà')
|
||||
|
@ -43,10 +43,9 @@ def get_basename(file_name):
|
|||
|
||||
# Chemin du dossier contenant les fichiers orgmode
|
||||
directory_pages = f'sources/{args.blog}/'
|
||||
directory_fr = f'sources/{args.blog}/lang_fr'
|
||||
directory_en = f'sources/{args.blog}/lang_en'
|
||||
|
||||
directories_to_scan = [directory_pages, directory_fr, directory_en]
|
||||
lang_fr = f'sources/{args.blog}/lang_fr'
|
||||
lang_en = f'sources/{args.blog}/lang_en'
|
||||
directories_to_scan = [directory_pages, lang_fr, lang_en]
|
||||
|
||||
destination_json = f'sources/{args.blog}/build'
|
||||
destination_html = f'html-websites/{args.blog}/'
|
||||
|
@ -87,6 +86,8 @@ if generate_linkings_json :
|
|||
# Parcourir les fichiers du dossier
|
||||
|
||||
for index, directory in enumerate(directories_to_scan):
|
||||
if directory == ".." or directory == "build" or directory == "templates" or directory == "img":
|
||||
continue
|
||||
# Déterminer le type d'article en fonction du chemin
|
||||
if directory == '/':
|
||||
article_type = "page"
|
||||
|
@ -96,6 +97,10 @@ if generate_linkings_json :
|
|||
if directory.split('/')[-1].startswith('lang_'):
|
||||
lang_folder = directory.split('/')[-1][5:] # Prend les caractères après "lang_"
|
||||
for file_name in os.listdir(directory):
|
||||
|
||||
# Vérifier si le fichier se termine par une extension supportée
|
||||
if not (file_name.endswith('.org') or file_name.endswith('.md') or file_name.endswith('.gmi')):
|
||||
continue
|
||||
if file_name.endswith('.org'):
|
||||
counter+=1
|
||||
if force_html_regen and counter % 10 == 0:
|
||||
|
@ -133,7 +138,9 @@ if generate_linkings_json :
|
|||
else:
|
||||
print(f"----------- last_html_build html_path: {html_path} n'existe pas")
|
||||
# Vérifier l'existence du fichier Gemini pour déterminer last_gemini_build
|
||||
gemini_path = f"gemini-capsules/{args.blog}/{slug}.gmi"
|
||||
os.makedirs(os.path.dirname(f"./gemini-capsules/{args.blog}/{annee}"), exist_ok=True)
|
||||
gemini_path = f"./gemini-capsules/{args.blog}/{annee}/{slug}.gmi"
|
||||
|
||||
last_gemini_build = None
|
||||
rebuild_this_article_gemini = False
|
||||
if os.path.exists(gemini_path):
|
||||
|
@ -187,13 +194,12 @@ if generate_linkings_json :
|
|||
html_content = content_without_h1
|
||||
|
||||
if run_gemini and rebuild_this_article_gemini:
|
||||
os.makedirs(destination_gmi, exist_ok=True)
|
||||
print('-----------on régénère le gemini')
|
||||
# convertir le contenu d'article org vers gmi pour la capsule gemini
|
||||
print(f"Conversion de {file_name} en gemini")
|
||||
gemini_content = org_to_gmi(content_without_h1, slug)
|
||||
|
||||
|
||||
|
||||
gemini_content = org_to_gmi(content_without_h1)
|
||||
print('len(gemini_content)', len(gemini_content))
|
||||
else:
|
||||
print('-----------on ne régénère pas le gemini')
|
||||
|
||||
|
||||
files_dict[f"{annee}/{slug}"] = {
|
||||
|
@ -259,7 +265,7 @@ os.makedirs(destination_json, exist_ok=True)
|
|||
json_file=destination_json+'/articles_info.json'
|
||||
|
||||
|
||||
|
||||
# sauver le json de tous les articles et pages
|
||||
if pandoc_runs_counter > 0 or not os.path.exists(json_file):
|
||||
print(f"\033[91m Les articles ont changé, Génération du json {json_file} \033[0m")
|
||||
with open( json_file, 'w', encoding='utf-8') as json_file:
|
||||
|
@ -270,10 +276,9 @@ if pandoc_runs_counter > 0 or not os.path.exists(json_file):
|
|||
|
||||
print(f"Nombre d'articles trouvés : {len(sorted_basenames)}")
|
||||
count_articles_updated = 0
|
||||
|
||||
current_year = datetime.now().year
|
||||
for basename, info in files_dict.items():
|
||||
date_str = info['date']
|
||||
current_year = datetime.now().year
|
||||
|
||||
if date_str > f'{current_year}0101':
|
||||
count_articles_updated += 1
|
||||
|
@ -314,7 +319,7 @@ def generate_blog_index(json_file, template_file, output_file):
|
|||
gmi_list_articles = ''
|
||||
|
||||
for basename, article in files_dict.items():
|
||||
gmi_list_articles += f"\n=> {article['slug']}.gmi "
|
||||
gmi_list_articles += f"\n=> {article['slug_with_year']}.gmi "
|
||||
|
||||
output_index_gmi = f"""
|
||||
# {template_content['BLOG_TITLE']}
|
||||
|
@ -349,6 +354,9 @@ Pages:
|
|||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
f.write(output_index_html)
|
||||
print(f"Page d'index générée dans {output_file}")
|
||||
|
||||
os.makedirs(os.path.dirname(gmi_index_file), exist_ok=True)
|
||||
print('gmi_index_file', gmi_index_file)
|
||||
with open(gmi_index_file, 'w', encoding='utf-8') as f:
|
||||
f.write(output_index_gmi)
|
||||
print(f"Page d'index gemini générée dans {gmi_index_file}")
|
||||
|
@ -372,48 +380,75 @@ def generate_article_pages(json_file, template_file, output_dir):
|
|||
:param template_file: Chemin du fichier template Jinja2.
|
||||
:param output_dir: Répertoire de sortie pour les fichiers HTML.
|
||||
"""
|
||||
|
||||
counter_gemini = 0
|
||||
print('generate_article_pages: ouverture du json')
|
||||
# Charger les données JSON
|
||||
try:
|
||||
# Charger les données JSON
|
||||
with open(json_file, 'r', encoding='utf-8') as f:
|
||||
print('----------------------- yay json chargé')
|
||||
articles_info = json.load(f)
|
||||
# Configurer Jinja2
|
||||
env = Environment(loader=FileSystemLoader('.'))
|
||||
template = env.get_template(template_file)
|
||||
template_content = get_blog_template_conf(args.blog)
|
||||
|
||||
# Générer les pages pour chaque article
|
||||
for article in articles_info.values():
|
||||
print('article', article['title'])
|
||||
|
||||
if article['first_picture_url']:
|
||||
template_content['OG_IMAGE'] = article['first_picture_url']
|
||||
else:
|
||||
template_content['OG_IMAGE'] = template_content['SITE_ICON']
|
||||
|
||||
output_html = template.render(
|
||||
template_content=template_content,
|
||||
article=article,
|
||||
all_articles=articles_info
|
||||
)
|
||||
slug_to_use = article['slug_with_year']
|
||||
|
||||
# Déterminer le slug à utiliser selon le type d'article
|
||||
if 'article_type' in article and article['article_type'] == 'article':
|
||||
slug_to_use = article['slug_with_year']
|
||||
else:
|
||||
slug_to_use = article['slug']
|
||||
# Construire le chemin de sortie html en fonction du slug avec l'année
|
||||
output_subdir = os.path.join(output_dir, slug_to_use)
|
||||
os.makedirs(output_subdir, exist_ok=True)
|
||||
output_file = os.path.join(output_subdir ,"index.html")
|
||||
# Écrire le fichier de sortie en HTML pour un article
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
f.write(output_html)
|
||||
|
||||
print(f"Génération de la page HTML pour {article['title']}")
|
||||
if 'gemini_content' in article and len(article['gemini_content']) > 0:
|
||||
# Construire le chemin de sortie gmi en fonction du slug avec l'année
|
||||
save_gemini_file(args.blog, article)
|
||||
counter_gemini += 1
|
||||
else:
|
||||
print(f"----------- on ne génère pas le gemini pour {article['slug']}")
|
||||
|
||||
print('generate_article_pages: fin de génération de l index')
|
||||
print(f"Nombre d'articles générés en gemini: {counter_gemini}")
|
||||
except FileNotFoundError:
|
||||
print(f"Erreur : Le fichier JSON {json_file} n'a pas été trouvé")
|
||||
return
|
||||
except json.JSONDecodeError:
|
||||
print(f"Erreur : Le fichier JSON {json_file} est mal formaté")
|
||||
return
|
||||
except Exception as e:
|
||||
print(f"Erreur lors de la lecture du fichier JSON : {str(e)}")
|
||||
return
|
||||
|
||||
with open(json_file, 'r', encoding='utf-8') as f:
|
||||
articles_info = json.load(f)
|
||||
|
||||
# Configurer Jinja2
|
||||
env = Environment(loader=FileSystemLoader('.'))
|
||||
template = env.get_template(template_file)
|
||||
template_content = get_blog_template_conf(args.blog)
|
||||
|
||||
# Générer les pages pour chaque article
|
||||
for article in articles_info.values():
|
||||
|
||||
if article['first_picture_url']:
|
||||
template_content['OG_IMAGE'] = article['first_picture_url']
|
||||
else:
|
||||
template_content['OG_IMAGE'] = template_content['SITE_ICON']
|
||||
|
||||
output_html = template.render(
|
||||
template_content=template_content,
|
||||
article=article,
|
||||
all_articles=articles_info
|
||||
)
|
||||
|
||||
# Construire le chemin de sortie en fonction du slug avec l'année
|
||||
output_subdir = os.path.join(output_dir, article['slug_with_year'])
|
||||
|
||||
os.makedirs(output_subdir, exist_ok=True)
|
||||
output_file = os.path.join(output_subdir ,"index.html")
|
||||
|
||||
|
||||
|
||||
# print(output_file)
|
||||
# Écrire le fichier de sortie
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
f.write(output_html)
|
||||
print('generate_article_pages: fin de génération de l index')
|
||||
|
||||
if pandoc_runs_counter:
|
||||
# if pandoc_runs_counter or run_gemini:
|
||||
# Appel de la fonction pour générer les pages des articles
|
||||
generate_article_pages(destination_json + '/articles_info.json', 'templates/html/article.html.jinja', destination_html)
|
||||
generate_article_pages(destination_json + '/articles_info.json', 'templates/html/article.html.jinja', destination_html)
|
||||
|
||||
# À la fin du script, calculer et afficher le temps d'exécution
|
||||
execution_time = time.time() - start_time
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue