init the repo with lots of work

main
Dorian 3 years ago
parent d500e246b4
commit d2b3f19664

2
.gitignore vendored

@ -0,0 +1,2 @@
output/*
venv/

@ -1,2 +1,52 @@
# www.moonwalks.be
# Moonwalks.be
## Editing content
The content files are in the `content/` directory.
`markdown` file exists in different languages, they're in `content/projects` (the texts presentation of the different projects) or `content/pages` (mainly the index, which is the intro + bio before the calendar).
Images can be dropped in the `content/gallery` folder, name as no importance, a plugin is going to resize them and sort them by hours of the day they were taken (using their metadata).
## Adding walk entries
The moonwalk calendar is a `.yaml` file, in `content/calendar/`.
To add a new entry:
1. open the website in a browser and go to the calendar to see what are the next New/Full moon dates
2. either copy the date by hand (with `-` between 2-digit numbers) or click on the date box on the calendar webpage (it will automatically copy it)
3. add a new entry in the `.yaml` by pasting the date (at one more indentation level than the `calendar:` key)
4. fill the other field like so:
```yaml
calendar:
#Full moon walk on the 18.03.22
18-03-22:
start_time: "18:00"
start_location: "Drève du comte"
start_location_link: "https://www.openstreetmap.org/way/14502214#map=17/50.79518/4.40096"
```
Everytime the webpage load it will first get the New/Full moon dates from the API, then see if any entries in the calendar matches one of those date and if it does, add the corresponding informations.
## Regenerate the website after editing content
Init steps
1. clone the repository
2. install pelican
On every updates
1. make your edits to the `content/` folder
2. `add`, `commit` and `push` your changes to the directory
3. open a terminal in the root folder of this project and launch the `pelican` command to regenerate
4. copy the new files generated in the `output/` folder to the server
if a change don't appear immediatly it's possible you have to hard refresh (using `ctrl`+`shift`+`r`).
<!-- ## Notes
* if location changes to another country it is possible that the previous walk doesn't correspond to their yaml (because the hour shift, make it jump one day before or after)
* we could do an automatic newsletter or RSS flux ? -->

@ -0,0 +1,28 @@
---
reservation_mail: "anais@anaisberck.be"
months_ahead: 3
latitude: 50.79493
longitude: 4.40250
timezone: "Europe/Brussels"
# -- test for california
# latitude: 36.7783
# longitude: -119.4179
# timezone: "America/Los_Angeles"
# https://www.timeanddate.com/moon/phases/usa/california-city
# it works !!
calendar:
#Full moon walk on the 18.03.22
18-03-22:
start_time: "18:00"
start_location: "Drève du comte"
start_location_link: "https://www.openstreetmap.org/way/14502214#map=17/50.79518/4.40096"
#New Moon walk on the 01.04.22
# 01-04-22:
# start_time: "19:30"
# start_location: "Drève du comte"
# start_location_link: "https://www.openstreetmap.org/way/14502214#map=17/50.79518/4.40096"

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 MiB

@ -0,0 +1,20 @@
{
"watch":{
"en": "Current moon phase",
"fr": "Phase lunaire actuelle",
"nl": "Huidige maanstand",
"sp": "Fase lunar actual"
},
"quotes":{
"en": "reactions participants",
"fr": "réactions participant.es",
"nl": "reacties deelnemers",
"sp": "reacciones participantes"
},
"projects":{
"en": "Projects",
"fr": "Projets",
"nl": "Projecten",
"sp": "Proyectos"
}
}

@ -0,0 +1,2 @@
Title: Gallery
template: gallery

@ -0,0 +1,4 @@
Title: Galerie
template: gallery
slug: gallery
lang: fr

@ -0,0 +1,4 @@
Title: Galerie
template: gallery
slug: gallery
lang: nl

@ -0,0 +1,4 @@
Title: Galería
template: gallery
slug: gallery
lang: sp

@ -0,0 +1,17 @@
Title: Calendar
save_as: index.html
slug: index
template: index
Walking when all the colours have disappeared from the forest is a special experience.
You tune in to other senses.
You discover silence, but you also notice movements and sounds that are absent during the day. Moreover, when you walk during the most intense and important moments of the lunar cycle, you can transform your intentions.
That is what these walks invite you to do.
We will walk in silence, interspersed with some experiments to which An invites you.
Each walk takes a maximum of 2 hours.
We conclude with a cup of tea.
<!--bio-->
The walks are an initiative of [Anaïs Berck](https://www.anaisberck.be), represented here by the thousands of trees of the Sonian forest and by artist, storyteller and nature guide An Mertens.

@ -0,0 +1,14 @@
Title: Calendrier
slug: index
lang: fr
template: index
Se promener lorsque toutes les couleurs ont disparu de la forêt est une expérience particulière.
Vous êtes à l'écoute dautres sens. Vous découvrez le silence, mais vous remarquez aussi des mouvements et des sons qui sont absents pendant la journée.
De plus, lorsque vous marchez pendant les moments les plus intenses et les plus importants du cycle lunaire, vous pouvez transformer vos intentions. C'est à cela que vous invitent ces marches.
Nous marcherons en silence, entrecoupés de quelques expériences auxquelles An vous invite. Chaque promenade dure au maximum 2 heures. Nous terminons en partageant un thé.
<!--bio-->
Les balades sont une initiative d'[Anaïs Berck](https://www.anaisberck.be), représentée ici par les milliers d'arbres de la forêt de Soignes et par l'artiste, conteuse et guide nature An Mertens.

@ -0,0 +1,68 @@
{
"about":{
"en": "About the walks",
"fr": "À propos des promenades",
"nl": "Over de wandelingen",
"sp": "Sobre los paseos"
},
"calendar":{
"en": "Moonwalks calendar",
"fr": "Calendrier des promenades lunaires",
"nl": "Kalender Maanwandelingen",
"sp": "Calendario de paseos lunares"
},
"datetime":{
"en": "Dates and times are given in",
"fr": "Les dates et heures sont indiquées en",
"nl": "Data en uren zijn vermeld in",
"sp": "Las fechas y horas se indican en"
},
"loading":{
"en": "Loading the calendar",
"fr": "Chargement du calendrier",
"nl": "Laden van de kalender",
"sp": "Cargar el calendario"
},
"signup":{
"en": "Sign up",
"fr": "S'inscrire",
"nl": "Reserveren",
"sp": "Reservar"
},
"notconfirmed":{
"en": "Not confirmed",
"fr": "Non confirmé",
"nl": "Niet bevestigd",
"sp": "No confirmado"
},
"start":{
"en": "Walk starts at",
"fr": "La marche commence à",
"nl": "De wandeling begint om",
"sp": "La caminata comienza a las"
},
"sunsetat":{
"en": "Sunset at",
"fr": "Coucher de soleil à",
"nl": "Zonsondergang om",
"sp": "Puesta de sol a las"
},
"moonat":{
"en": "Moon event at",
"fr": "Événement lunaire à",
"nl": "Maangebeuren om",
"sp": "Evento lunar a las"
},
"mailsubject":{
"en": "$ walk on the",
"fr": "Balade de $ le",
"nl": "$ wandeling op",
"sp": "Paseo de $ el"
},
"more":{
"en": "More to come",
"fr": "Plus à venir",
"nl": "Wordt vervolgd",
"sp": "Más por venir"
}
}

@ -0,0 +1,14 @@
Title: Kalender
slug: index
lang: nl
template: index
Wandelen wanneer alle kleurtjes uit het bos verdwenen zijn, is een bijzondere ervaring.
Je stelt in op andere zintuigen. Je ontdekt de stilte, maar je merkt ook bewegingen en geluiden op die overdag afwezig zijn.
Wanneer je bovendien wandelt tijdens de meest intense en belangrijke momenten van de maancyclus, kan je je intenties transformeren. Dat is waartoe deze wandelingen je uitnodigen.
We wandelen in stilte, afgewisseld met enkele experimenten waartoe An je uitnodigt. Elke wandeling duurt maximum 2 uur. We sluiten af met een kopje thee.
<!--bio-->
De wandelingen zijn een initiatief van [Anaïs Berck](https://www.anaisberck.be), hier vertegenwoordigd door de duizenden bomen van het Zoniënwoud en door kunstenaar, verteller en natuurgids An Mertens.

@ -0,0 +1,14 @@
Title: Calendario
slug: index
lang: sp
template: index
Caminar cuando todos los colores han desaparecido del bosque es una experiencia especial.
Se sintoniza con otros sentidos. Descubres el silencio, pero también percibes movimientos y sonidos que son ausentes durante el día.
Además, cuando caminas en los momentos más intensos e importantes del ciclo lunar, puedes transformar tus intenciones. A eso te invitan estos paseos.
Caminaremos en silencio, intercalando algunos experimentos a los que An te invita. Cada paseo dura un máximo de 2 horas. Concluimos con un té.
<!--bio-->
Los paseos son una iniciativa de [Anaïs Berck](https://www.anaisberck.be), representada aquí por los miles de árboles del Sonian Forest y por la artista, contadora y guía de la naturaleza An Mertens.

@ -0,0 +1,9 @@
Title: Individual walks
Nature always offers healing if you are looking for it. A guide can help you. That is the purpose of the individual walk. You have a question and you go to work on it. For two or three hours. Each walk is unique and tailored to you.
## Guide
As a guide, An offers various methods. She draws on her experiences with reiki, shamanic work and her activities as a nature guide and artist. Through a combination of spiritual and scientific biological perspectives, she leads you on your personal journey through the Sonian forest, a forest whose subsoil has always been forest, since the last Ice Age more than ten thousand years ago. And you can feel that.
## Biodiversity
A squirrel rustling in the canopy of a beech tree, a jay flying overhead, the fruit laden branches of the elder drawing your attention... The forest is a world of abundance and each element can contribute metaphorically to the solution of your problem, in the short or long term.

@ -0,0 +1,11 @@
Title: Balade Individuelle
slug: individual-walks
lang: fr
La nature offre toujours la guérison si vous la recherchez. Un guide peut vous aider. C'est le but de la balade individuelle. Vous avez une question et vous vous lancez. Pendant deux ou trois heures. Chaque promenade est unique et adaptée à vous.
## Guide
En tant que guide, An propose différentes méthodes. Elle s'appuie sur ses expériences avec le reiki, le travail chamanique et ses activités de guide nature et d'artiste. En combinant des perspectives spirituelles et scientifiques, elle vous conduit dans votre voyage personnel à travers la forêt de Soignes, une forêt dont le sous-sol a toujours été forestier, depuis la dernière période glaciaire, il y a plus de dix mille ans. Et vous pouvez le sentir.
## Biodiversité
Un écureuil bruissant dans la canopée d'un hêtre, un geai des chênes volant au-dessus de votre tête, les branches chargées de fruits du sureau attirant votre attention... La forêt est un monde d'abondance et chaque élément peut contribuer métaphoriquement à la solution de votre problème, à court ou à long terme.

@ -0,0 +1,11 @@
Title: Individuele Wandeling
slug: individual-walks
lang: nl
De natuur biedt altijd heling als je ernaar op zoek bent. Een gids kan je daarbij helpen. Dat is het opzet van de individuele wandeling. Je hebt een vraagstuk en daar ga je mee aan de slag. Twee of drie uur lang. Elke tocht is uniek en op jou afgestemd.
## Gids
Als gids biedt An verschillende methodes aan. Daarvoor put ze uit haar ervaringen met reiki, sjamanistisch werk en haar activiteiten als natuurgids en kunstenaar. Via een combinatie van spirituele en wetenschappelijk biologische perpectieven leidt ze je op je persoonlijke reis door het Zoniënwoud, een bos waarvan de ondergrond altijd bos is geweest, sinds de laatste Ijstijd meer dan tienduizend jaar geleden. En dat voel je.
## Biodiversiteit
Een eekhoorn die ritselend in de kruin van een beuk zijn weg vindt, een Vlaamse gaai die overvliegt, de met vruchten beladen takken van de vlier die je aandacht trekken… Het bos is een wereld van overvloed en elk element kan metaforisch bijdragen tot de oplossing van je vraagstuk, op korte of langere termijn.

@ -0,0 +1,11 @@
Title: Paseo individual
slug: individual-walks
lang: sp
La naturaleza siempre ofrece curación si la buscas. Un guía puede ayudarte. Ese es el objetivo del paseo individual. Tienes una pregunta y te pones a trabajar en ella. Durante dos o tres horas. Cada paseo es único y se adapta a ti.
## Guía
Como guía, An ofrece varios métodos. Se basa en sus experiencias con el reiki, el trabajo chamánico y sus actividades como guía de naturaleza y artista. A través de una combinación de perspectivas espirituales y científicas, te conduce en tu viaje personal por el Sonian Forest, un bosque cuyo subsuelo siempre ha sido bosque, desde la última Edad de Hielo, hace más de diez mil años. Y eso se siente.
## Biodiversidad
Una ardilla susurrando en la copa de un haya, un arrendajo volando sobre tu cabeza, las ramas cargadas de frutos del saúco llamando tu atención... El bosque es un mundo de abundancia y cada elemento puede contribuir metafóricamente a la solución de tu problema, a corto o largo plazo.

@ -0,0 +1,32 @@
Title: Moonwalks
## New rituals
Botanist and Native American Indian Robin Wall Kimmerer states in her book “Braiding Sweetgrass” that the core of the climate crisis is related to losing the connection with the land. By reconnecting, a form of recovery of the land and its people can take place, as well as a sustainable caring for. The connection can be made in various ways, for example by taking responsibility for a piece of land, be it as a vegetable garden, ornamental garden or forest. Her hypothesis is that a person's physical, emotional and spiritual health improves greatly when the relationship with the land is reinstated in his/her life. She urges the creation of new rituals that promote such relationships. The moon walks try to be such a new ritual.
## Polyocene
Psychologist and philosopher Vinciane Despret, known for her books “Autobiographie d'un Poulpe” and “Habiter en oiseau”, proposes to no longer speak of the Anthropocene, which carries a dystopian connotation, but of the Polyocene, the proposal to start living from the idea that we as humans do not live alone on this planet. We are part of a polyphony, and we need to ask ourselves how we can better live together, and even more, create together with the more-than-human beings. It is important to de-centre our gaze so that we can create such relationships. The forest helps with this.
## Brussels
These are just two of the authors who specifically point to the end of anthropocentrism, and also to the personal well-being that we can develop if we dare to enter into relationships with non-human beings. In Brussels, we are lucky to have a large forest close by, the Sonian Forest. Moreover, it is not just any forest. It has always been a forest since the last ice age more than 10000 years ago. And even though the trees were replanted by Zinner in the 18th century, the forest still retains that special energy that characterises places where trees are the main inhabitants.
## Full and New Moonwalks
These and other authors inspired me to organise - as a new ritual - new and full moon walks. I have been doing this since the spring of 2021. They are walks that combine elements from forest bathing, meditation and guided nature walks.
<!--quotes-->
> I enjoyed the mixture of different ingredients: biology, fiction, politics... I also liked the silence, and the intensity of the experience. The space, for example, seemed very vast to me (I know the place well, I know we didn't walk miles and yet it seemed long, dense: a journey). I also found it very nice to see/feel the night appearing, and to realise that I was not afraid. Because I was with you? Because the trees had given me a friendly welcome?
>
> Rafaella
<!-- -->
> What I have kept as strong memories are the shapes and colours that changed during the walk, and also the sounds: our footsteps in silence on the gravel, and the birds. We both cherish the intention we set during the moment you dedicated to the new moon. It was strong. We think it is important to keep that alive.
>
> Doriane & Zeste
<!-- -->
> I was coming out of a very busy day and the walk calmed me down. In the beginning I had trouble concentrating on what the invitations were, because my head was still processing all the impressions of the day, but towards the end I was totally into it.
>
> Delphine

@ -0,0 +1,34 @@
Title: Balades lunaires
slug: moonwalks
lang: fr
## Nouveaux rituels
La botaniste et amérindienne Robin Wall Kimmerer affirme dans son livre «Les herbes sacrées» que le noyau de la crise climatique est lié à la perte du lien avec la terre. En se reconnectant, une forme de récupération de la terre et de ses habitants peut avoir lieu, ainsi qu'une prise de soin durable. Le lien peut être établi de différentes manières, par exemple en prenant la responsabilité d'un terrain, qu'il s'agisse d'un potager, d'un jardin d'ornement ou d'une forêt. Son hypothèse est que la santé physique, émotionnelle et spirituelle d'une personne s'améliore considérablement lorsque la relation avec la terre est rétablie dans sa vie. Elle préconise la création de nouveaux rituels qui favorisent ces relations. Les balades lunaires essaient dêtre un nouveau rituel.
## Polycène
La psychologue et philosophe Vinciane Despret, connue pour ses livres «Autobiographie d'un Poulpe» et «Habiter en oiseau», propose de ne plus parler de l'Anthropocène, qui a une connotation dystopique, mais de Polyocène, la proposition de commencer à vivre à partir de l'idée que nous, les humains, ne vivons pas seuls sur cette planète. Nous faisons partie d'une polyphonie, et nous devons nous demander comment mieux vivre ensemble, et plus encore, créer ensemble avec les êtres plus qu'humains. Il est important de décentrer notre regard afin de pouvoir créer de telles relations. Vivre la présence de la forêt y contribue.
## Bruxelles
Ce ne sont là que deux des auteurs qui soulignent spécifiquement la fin de l'anthropocentrisme, mais aussi le bien-être personnel que nous pouvons développer si nous osons entrer en relation avec des êtres non humains. A Bruxelles, nous avons la chance d'avoir une grande forêt à notre disposition, la forêt de Soignes. En outre, il ne s'agit pas de n'importe quelle forêt. Elle a toujours été forêt depuis la dernière période glaciaire, il y a plus de 10 000 ans. Et même si les arbres ont été replantés par Zinner au XVIIIe siècle, la forêt conserve cette énergie particulière qui caractérise les lieux où les arbres sont les principaux habitants.
## Balades de pleine et nouvelle lune
Ces auteurs et d'autres m'ont inspiré l'idée d'organiser - comme un nouveau rituel - des promenades à la nouvelle et à la pleine lune. Je fais ceci depuis le printemps 2021. Ce sont des promenades à mi-chemin entre le bain de forêt, la méditation et les promenades guidées dans la nature.
<!--quotes-->
> J'ai aimé le mélange entre les différents éléments de la narration: entre biologie, fiction, politique... J'ai aussi beaucoup aimé le silence, et puis la densité de l'expérience. L'espace, par exemple, m'a semblé très dilaté (je connais bien l'endroit, je sais qu'on n'a pas marché pendant des kilomètres et pourtant ça m'a paru long, dense: un voyage). J'ai aussi beaucoup aimé voir/ sentir la nuit tomber, et me rendre compte que je n'avais pas peur. Parce que j'étais avec vous? Parce que les arbres m'avaient souhaité bienvenue avec bienveillance?
>
> Rafaella
<!-- -->
> Ce qu'il me reste comme souvenirs forts, ce sont les formes et les couleurs qui se métamorphosent progressivement le long de la balade, ainsi que les sons: ceux de nos pas en silence sur les graviers, et des oiseaux. Nous gardons tout.e.s les deux en nous l'intention que nous avons pu placer dans le moment dédié à la nouvelle lune, c'était fort et cela nous tient à cœur de la garder dans notre vie.
>
> Doriane & Zeste
<!-- -->
> Je sortais d'une journée très chargée et la promenade m'a calmée. Au début, j'avais du mal à me concentrer sur les invitations, parce que ma tête était encore en train de traiter toutes les impressions de la journée, mais vers la fin, j'étais complètement dedans.
>
> Delphine

@ -0,0 +1,34 @@
Title: Maanwandelingen
slug: moonwalks
lang: nl
## Nieuwe rituelen
Botaniste en Native American Indian Robin Wall Kimmerer stelt in haar boek “Braiding Sweetgrass”, dat de kern van de klimaatcrisis te maken heeft met het verliezen van de verbinding met het land. Door de verbinding weer aan te gaan, kan er ook een vorm van herstel van het land en de mensen plaatsvinden en een duurzaam zorg-dragen-voor. De verbinding kan op verschillende manieren gemaakt worden, bijvoorbeeld door de verantwoordelijkheid te nemen voor een stuk grond, zij het als moestuin, siertuin of bos. Haar hypothese is dat zowel de fysieke, de emotionele als de spirituele gezondheid van een persoon sterk verbetert als de relatie met het land weer een plaats krijgt in zijn/haar leven. Ze dringt erop aan om nieuwe rituelen in het leven te roepen, die die relaties bevorderen. De maanwandelingen proberen om zon nieuw ritueel te zijn.
## Polyceen
Psychologe en filosofe Vinciane Despret, bekend van haar boeken “Autobiographie d'un Poulpe” en “Habiter en oiseau” stelt voor om niet meer te spreken van de Antropoceen, die een dystopische connotatie in zich draagt, maar van de Polyceen, het voorstel om te gaan leven vanuit de idee dat we als mensen niet alleen op deze planeet leven. We zijn deel van een meerstemmigheid, en we moeten ons afvragen hoe we beter kunnen samenleven, en meer nog, samen creëren met de meer-dan-menselijke wezens. Het is belangrijk om onze blik te decentreren, zodat we zo'n relaties kunnen aangaan. Het bos helpt daarbij.
## Brussel
Dit zijn maar twee van de auteurs die specifiek wijzen op het einde van het antropocentrisme, en ook op het persoonlijke welzijn dat we kunnen ontwikkelen als we in relatie durven gaan met andere dan menselijke wezens. In Brussel hebben we het geluk van een groot bos ter beschikking te hebben, het Zoniënwoud. Bovendien is het niet zomaar een bos. De ondergrond is sinds de laatste ijstijd meer dan 10000 jaar geleden altijd bos geweest. En ook al zijn de bomen heraangeplant door Zinner in de 18de eeuw, toch blijft het bos die speciale energie behouden die plekken kenmerkt, waar bomen de belangrijkste bewoners zijn.
## Volle en Nieuwe Maanwandelingen
Deze en andere auteurs inspireerden me om als een nieuw ritueel - nieuwe en volle maanwandelingen te organiseren. Ik doe dit sinds de lente van 2021. Het zijn wandelingen die het midden houden tussen bosbaden, meditatie en geleide natuurwandelingen.
<!--quotes-->
> Ik heb genoten van de mix van verschillende ingrediënten: biologie, fictie, politiek... Ik hield ook van de stilte, en de intensiteit van de ervaring. De ruimte, bijvoorbeeld, leek mij heel uitgestrekt (ik ken de plaats goed, ik weet dat wij geen kilometers hebben gelopen en toch leek het lang, intens: een reis). Ik vond het ook heel fijn om de nacht te zien/voelen verschijnen, en te beseffen dat ik niet bang was. Omdat ik bij jou was? Omdat de bomen me vriendelijk welkom hadden geheten?
>
> Rafaella
<!-- -->
> Wat ik als sterke herinneringen heb overgehouden, zijn de vormen en kleuren die veranderden tijdens de wandeling, en ook de geluiden: onze voetstappen in stilte op het grind, en de vogels. We koesteren allebei de intentie die we plaatsten tijdens het moment dat je wijdde aan de nieuwe maan. Dat was sterk. We vinden het belangrijk om dat levendig te houden.
>
> Doriane & Zeste
<!-- -->
> Ik kwam uit een heel drukke dag en de wandeling heeft me terug rustig gemaakt. In het begin had ik moeite om me te concentreren op wat de opdrachten waren, omdat mn hoofd nog alle indrukken van de dag aan het verwerken was, maar naar het einde toe zat ik er helemaal in.
>
> Delphine

@ -0,0 +1,35 @@
Title: Paseos lunares
slug: moonwalks
lang: sp
## Nuevos rituales
La botánica e india americana Robin Wall Kimmerer afirma en su libro «Braiding Sweetgrass» que el núcleo de la crisis climática está relacionado con la pérdida de la conexión con la tierra. Al reconectar, puede producirse una forma de recuperación de la tierra y su gente, así como un cuidado sostenible. La conexión puede hacerse de varias maneras, por ejemplo, responsabilizándose de un trozo de tierra, ya sea un huerto, un jardín ornamental o un bosque. Su hipótesis es que la salud física, emocional y espiritual de una persona mejora enormemente cuando se restablece la relación con la tierra en su vida. Insta a crear nuevos rituales que promuevan esas relaciones. Los paseos lunares intentan ser un nuevo ritual.
## Polyocene
La psicóloga y filósofa Vinciane Despret, conocida por sus libros «Autobiographie d'un Poulpe» y «Habiter en oiseau», propone que ya no se hable del Antropoceno, que tiene una connotación distópica, sino del Polioceno, la propuesta de empezar a vivir desde la idea de que los humanos no vivimos solos en este planeta. Somos parte de una polifonía, y tenemos que preguntarnos cómo podemos convivir mejor, y más aún, crear junto a los seres más-que-humanos. Es importante descentrar nuestra mirada para poder crear esas relaciones. Vivir experiencias en el bosque ayuda a ello.
## Bruselas
Estos son sólo dos de los autores que apuntan específicamente al fin del antropocentrismo, y también al bienestar personal que podemos desarrollar si nos atrevemos a entrar en relación con los seres más que humanos. En Bruselas, tenemos la suerte de contar con un gran bosque cerca, el Sonian Forest. Además, no es un bosque cualquiera. Siempre ha sido un bosque desde la última Edad de Hielo, hace más de 10000 años. Y aunque los árboles fueron replantados por Zinner en el siglo XVIII, el bosque sigue conservando esa energía especial que caracteriza a los lugares donde los árboles son los principales habitantes.
## Paseos de luna llena y nueva
Estos y otros autores me inspiraron a organizar -como un nuevo ritual- paseos de luna nueva y llena. Llevo haciéndolo desde la primavera de 2021. Son paseos que combinan elementos de baños de bosque, meditación y paseos guiados por la naturaleza.
<!--quotes-->
> Me gustó la mezcla de diferentes ingredientes: biología, ficción, política... También me gustó el silencio, y la intensidad de la experiencia. El espacio, por ejemplo, me pareció muy vasto (conozco bien el lugar, sé que no hicimos kilómetros y, sin embargo, me pareció largo, denso: un viaje). También me pareció muy agradable ver/sentir la aparición de la noche, y darme cuenta de que no tenía miedo. ¿Porque estaba con vosotros? ¿Porque los árboles me habían dado una bienvenida amistosa?
>
> Rafaella
<!-- -->
> Lo que he guardado como fuertes recuerdos son las formas y los colores que cambiaron durante el paseo, y también los sonidos: nuestras pisadas en silencio sobre la grava, y los pájaros. Les dos guardamos la intención que pusimos durante el momento que le dedicaste a la luna nueva. Fue muy fuerte. Creemos que es importante mantenerla viva.
>
> Doriane & Zeste
<!-- -->
> Salí de un día muy ajetreado y el paseo me calmó. Al principio me costó concentrarme en lo que eran las invitaciones, porque mi cabeza aún estaba procesando todas las impresiones del día, pero hacia el final estaba totalmente metida en ello.
>
> Delphine

@ -0,0 +1,12 @@
Title: Nature theatre
Nature theatre is a play that does not take place between four walls, but in the forest; where the actors are not people, but more-than-humans like trees, mosses or plants, and where the audience has its own input into the catharsis of the play. You can register for this as a group.
## Nature theatre?
Nature theatre takes place in nature, plays with the elements of nature and aims to renew the relationship between human and nature. Nature theatre is sensory theatre, which appeals to the five senses of the audience. It is interactive theatre, to be understood as an interactive walk with experiments and stories. It is intuitive theatre, non-intellectual. The audience's own imagination and the sharing of it provide emotional, transforming content. Nature provides the mirror, the wisdom of the group creates the catharsis.
## Set up
As a dramaturge, An offers ingredients such as poetic texts, metaphorical information about celestial bodies and actors from the forest, walking in silence, guided meditations, physical exercises, observation through the five senses, empathy... Different levels of deepening are possible, for audiences who participate in the nature theatre several times.
## Anaïs Berck
Nature theatre is a project by Anaïs Berck, a pseudonym that stands for the collaboration between people, algorithms and trees. In this case, we explore the space between plant and human intelligence, in collaboration with the trees of the Sonian forest and with artist, storyteller and nature guide An Mertens.

@ -0,0 +1,14 @@
Title: Théâtre de nature
slug: nature-theatre
lang: fr
Le théâtre de nature est une pièce qui ne se déroule pas entre quatre murs, mais dans la forêt, où les acteurs ne sont pas des personnes, mais des plus-que-hommes, et où le public participe à la catharsis de la pièce. Vous pouvez vous inscrire en tant que groupe.
## Théâtre de nature ?
Le théâtre de nature se déroule dans la nature, il joue avec les éléments de la nature et il vise à renouveler la relation entre l'homme et la nature. Le théâtre de nature est un théâtre sensoriel, qui fait appel aux cinq sens du public. Il s'agit d'un théâtre interactif, à comprendre comme une promenade interactive avec des missions et des histoires. C'est un théâtre intuitif, non intellectuel. L'imagination du public et le partage de celle-ci fournissent un contenu émotionnel et transformateur. La nature fournit le miroir, la sagesse du groupe crée la catharsis.
## Accompagnement
En tant que dramaturge, An propose des ingrédients tels que des textes poétiques, des informations métaphoriques sur les corps célestes et les acteurs de la forêt, la marche en silence, des méditations guidées, des exercices physiques, l'observation par les cinq sens, l'empathie... Différents niveaux d'approfondissement sont possibles, pour les spectateurs qui participent plusieurs fois au théâtre de nature.
## Anaïs Berck
Théâtre de nature est un projet d'[Anaïs Berck](https://www.anaisberck.be), un pseudonyme qui représente la collaboration entre les personnes, les algorithmes et les arbres. Dans ce cas, nous explorons l'espace entre l'intelligence végétale et humaine, en collaboration avec les arbres de la forêt de Soignes et avec l'artiste, conteuse et guide de nature An Mertens.

@ -0,0 +1,14 @@
Title: Natuurtheater
slug: nature-theatre
lang: nl
Natuurtheater is een theaterstuk dat zich niet tussen vier muren afspeelt, maar in het bos; waarin de acteurs geen mensen zijn, maar meer-dan-mensen, en waarin het publiek een eigen inbreng heeft in de katharsis van het stuk. Je kan je hiervoor inschrijven als groep.
## Natuurtheater?
Natuurtheater speelt zich af in de natuur, het speelt met de natuurelementen en het beoogt de hervernieuwing van de relatie tussen mens en natuur. Natuurtheater is sensorieel theater, waarbij de vijf zintuigen van het publiek aangesproken worden. Het is interactief theater, te begrijpen als een interactieve wandeling met opdrachten en verhalen. Het is intuïtief theater, niet-intellectueel. De eigen fantasie van het publiek en het delen daarvan zorgen voor emotionele, transformerende invulling. De natuur biedt de spiegel, de wijsheid van de groep creëert de catharsis.
## Opzet
Als dramaturg biedt An ingrediënten aan, zoals poëtische teksten, metaforische informatie over hemellichamen en acteurs uit het bos, wandelen in stilte, geleide meditaties, fysieke oefeningen, observatie via de vijf zintuigen, inleving... Er zijn verschillende niveaus van verdieping mogelijk, voor publieken die meermaals deelnemen aan het natuurtheater.
## Anaïs Berck
Natuurtheater is een project van [Anaïs Berck](https://www.anaisberck.be), een pseudoniem dat staat voor de samenwerking tussen mensen, algoritmes en bomen. In dit geval exploreren we de ruimte tussen plantaardige en menselijke intelligentie, in samenwerking met de bomen van het Zoniënwoud en met kunstenaar, verteller en natuurgids An Mertens.

@ -0,0 +1,14 @@
Title: Teatro de naturaleza
slug: nature-theatre
lang: sp
El teatro de naturaleza es una obra que no se desarrolla entre cuatro paredes, sino en el bosque; donde los actores no son personas, sino más que humanos, como árboles, musgos o plantas, y donde el público contribuye a la catarsis de la obra. Puedes inscribirte en grupo.
## ¿Teatro de naturaleza?
El teatro de naturaleza se desarrolla en la naturaleza, juega con los elementos de la misma y pretende renovar la relación entre el ser humano y la naturaleza. El teatro de la naturaleza es un teatro sensorial, que apela a los cinco sentidos del público. Es un teatro interactivo, que debe entenderse como un paseo interactivo con experimentos e historias. Es un teatro intuitivo, no intelectual. La propia imaginación del público y el hecho de compartirla proporcionan un contenido emocional y transformador. La naturaleza proporciona el espejo, la sabiduría del grupo crea la catarsis.
## Ingredientes
Como dramaturgo, An ofrece ingredientes como textos poéticos, información metafórica sobre cuerpos celestes y actores del bosque, paseos en silencio, meditaciones guiadas, ejercicios físicos, observación a través de los cinco sentidos, empatía... Diferentes niveles de profundización son posibles, para el público que participa varias veces en el teatro de naturaleza.
## Anaïs Berck
El teatro de naturaleza es un proyecto de [Anaïs Berck](https://www.anaisberck.be), un seudónimo que representa la colaboración entre personas, algoritmos y árboles. En este caso, exploramos el espacio entre la inteligencia vegetal y la humana, en colaboración con los árboles del Sonian Forest y con la artista, contadora y guía de la naturaleza An Mertens.

@ -0,0 +1,159 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Anaïs Berck'
SITENAME = 'Moonwalks.be'
SITEURL = ''
PATH = 'content'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Pelican', 'https://getpelican.com/'),
('Python.org', 'https://www.python.org/'),
('Jinja2', 'https://palletsprojects.com/p/jinja/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = False
# Uncomment following line if you want document-relative URLs when developing
# RELATIVE_URLS = True
# CUSTOM PAREMETERS
# ==============================================================================
# a page work like that 1 md file = 1 template
# an article for like that
# theme path
THEME = 'theme'
# ARCHITECTURE
# ==============================================================================
# 3 categories (calendar, projects, gallery)
# those categories serves as navigation (in base.html):
# - iterate through the list to generate nav menu
# - put as active if current article category is cat menu item
# every category is exactly one template
USE_FOLDER_AS_CATEGORY = True
ARTICLE_PATHS = ['projects/'] # exclude articles outside of this
# however we add the metadata "save_as: '' " to the calendar/ one
# so they're available through the articles variable, but not saved as independant file
# (status: hidden) does the opposite (save the page, but unlist it)
ARTICLE_SAVE_AS = '{category}/{slug}.html'
ARTICLE_URL = '/{category}/{slug}.html'
ARTICLE_LANG_SAVE_AS = '{category}/{slug}_{lang}.html'
ARTICLE_LANG_URL = '/{category}/{slug}_{lang}.html'
# pages have no category
PAGE_SAVE_AS = '{slug}.html'
PAGE_URL = '/{slug}.html'
PAGE_LANG_SAVE_AS = '{slug}_{lang}.html'
PAGE_LANG_URL = '/{slug}_{lang}.html'
SLUGIFY_SOURCE = 'title'
CATEGORY_URL = '{slug}/'
# disable the generation of those default html files
CATEGORY_SAVE_AS = ''
AUTHOR_SAVE_AS = ''
TAG_SAVE_AS = ''
# the "collections" type html pages that we want
# DIRECT_TEMPLATES = ['index', 'authors', 'categories', 'tags', 'archives']
# because gallery and even index is a page
# (this allow to have translation for index_fr, index_nl, etc)
DIRECT_TEMPLATES = []
# to copy every image to the output direction
STATIC_PATHS = ['gallery']
MENUITEMS = [
# ("calendar", "/index.html"),
]
# TRANSLATION
# ==============================================================================
# only article with this lang will be listed
DEFAULT_LANG = 'en'
# two article with same slug are considered as translation:
# ARTICLE_TRANSLATION_ID = 'slug'
# by default slug is generated from title:
# SLUGIFY_SOURCE = 'title'
# which means the translated article have to have the same title
# but the title is going to be translated, so by default
# the best way is to setup slug metadata manually so it fit the english slugification
PAGE_TRANSLATION_ID = 'slug'
# DATE
# ==============================================================================
TIMEZONE = 'Europe/Paris'
# by default pelican asks for a date for every article (?)
DEFAULT_DATE = 'fs'
# PLUGINS
# ==============================================================================
PLUGIN_PATHS = ['plugins']
PLUGINS = ['quotes-section', 'data_files', 'gallery','image_process','multilang-json-page']
# --- quotes-sections (self made)
# separate an article when meeting <!--quotes-->
# put the first section in the article.content variable
# put the second section in the article.quotes variable
# TODO: generalize it for every short text in comment as different "section"
# --- data_files (from: https://github.com/LucasVanHaaren/pelican-data-files, with custom added YAML support)
# by parse the json and yaml file in the data/ directory and add them tp the context
# as object with name "DATA_[filename]"
DATA_FILES_DIR = "calendar/"
# --- gallery
# create a GALLERY global variable list of urls for img contained in the /gallery/ folder
# and parse their exifs data to add the date on which they were taken
# --- image_process (from: https://github.com/pelican-plugins/image-process)
# note: we can add the class manually in the html template (and not in the markdown)
IMAGE_PROCESS = {
# reminder on srctset
# https://www.youtube.com/watch?v=2QYpkrX2N48&ab_channel=KevinPowell
# our gallery <img> html element varies between
# 300 and 500 browser pixels width
# so on 1x devices we give it a 500px image to be sure
"gallery": {
"type": "responsive-image",
# Here we could actually precise the size of the <img> html element with media query
# then we have to replace the 1x, 2x with actual px width of the image element
# "sizes": (
# "500px"
# ),
"srcset": [
# first parameter is to inform the browser of the image file size (with the w unit)
# or just precising the display subpixel type
# !before! it has to actually download the image
("1x", ["scale_in 500 500 True"]),
("2x", ["scale_in 1000 1000 True"])
],
"default": "1x"
}
}

@ -0,0 +1,6 @@
from pelican import signals
from .generators import get_generators
def register():
signals.get_generators.connect(get_generators)

@ -0,0 +1,3 @@
JSON = {"name": "json", "extensions": [".json"]}
YAML = {"name": "yaml", "extensions": [".yaml", ".yml"]}
XML = {"name": "xml", "extensions": [".xml"]}

@ -0,0 +1,138 @@
import logging
import pathlib
import json
import yaml
from yaml.loader import SafeLoader
from sys import exit
from pelican.generators import Generator
from .file_formats import JSON, YAML
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
class DataGenerator(Generator):
"""
Load data from files
"""
SUPPORTED_FORMATS = [JSON, YAML]
CONTEXT_PREFIX = "DATA_"
def __init__(
self,
context,
settings,
path,
theme,
output_path,
readers_cache_name="",
**kwargs,
):
super().__init__(
context,
settings,
path,
theme,
output_path,
readers_cache_name=readers_cache_name,
**kwargs,
)
log.info("PLUGIN: pelican-data-files was successfully loaded")
self.settings.setdefault("DATA_FILES_DIR", "data")
def _is_valid_file(self, file):
"""Checks if file format is supported.
params:
- file -- pathlib.Path object
"""
for file_format in self.SUPPORTED_FORMATS:
if file.suffix in file_format["extensions"]:
return True
return False
def _get_data_files(self):
"""Return list of valid files to load into context"""
data_dir = pathlib.Path(self.settings["DATA_FILES_DIR"])
valid_files = []
# turn path into absolute if not already
if not data_dir.is_absolute():
data_dir = pathlib.Path(self.settings["PATH"]).joinpath(data_dir)
# check if path exists
if not data_dir.exists():
log.error("pelican-data-files: DATA_FILES_DIR path doesn't exists.")
exit(1)
if not data_dir.is_dir():
log.error("pelican-data-files: DATA_FILES_DIR path isn't a directory.")
exit(1)
# return all valid files in path
# TODO check for duplicates (eg: profile.json and profile.yaml)
for file in data_dir.iterdir():
if self._is_valid_file(file):
valid_files.append(file)
return valid_files
def _format_filename(self, file):
"""Format context var name from filename.
params:
- file -- pathlib.Path object
"""
return file.stem.replace(".", "_").upper()
def _read_file(self, file):
"""Read and parse data from file.
params:
- file -- pathlib.Path object
"""
with file.open() as f:
for file_format in self.SUPPORTED_FORMATS:
if file_format["name"] == "json" and file.suffix in file_format["extensions"]:
try:
return json.load(f)
except ValueError:
return None
elif file_format["name"] == "yaml" and file.suffix in file_format["extensions"]:
try:
return yaml.load(f, Loader=SafeLoader)
except ValueError:
return None
def _add_data_to_context(self, name, data):
"""Add data into context.
params:
- name -- str
- data -- dict
"""
ctx_name = self.CONTEXT_PREFIX + name
self.context[ctx_name] = data
def generate_context(self):
"""Generate context from data files"""
for file in self._get_data_files():
name = self._format_filename(file)
data = self._read_file(file)
if data:
self._add_data_to_context(name, data)
log.info(f"{file.name} was loaded.")
else:
log.error(f"{file.name} wasn't loaded.")
def get_generators(pelican_object):
return DataGenerator

@ -0,0 +1,109 @@
import argparse
import shutil
import sys
from pathlib import Path
def _err(msg, die=None):
"""Print an error message and exits if an exit code is given"""
sys.stderr.write(f"ERROR: {msg}\n")
if die:
sys.exit(die if type(die) is int else 1)
try:
import pelican
except ImportError:
_err(
"Cannot import pelican.\nYou must "
"install Pelican in order to run this script.",
1,
)
# where data files are stored in pelican-data-files's compatible theme
SRC_DATA_DIR = "data"
# where data file are copied in pelican project directory
DEST_DATA_DIR = "data"
PELICAN_ROOT_DIR = Path(pelican.__file__).absolute().parent
PELICAN_THEMES_DIR = PELICAN_ROOT_DIR.joinpath("themes")
def _parse_args():
"""Parse and return cli arguments"""
parser = argparse.ArgumentParser(
description="""List and fetch data files from compatible themes"""
)
parser.add_argument(
"-l",
"--list",
action="store_true",
help="list all themes compatible with this plugin",
)
parser.add_argument(
"-f",
"--fetch",
type=str,
metavar="THEME_NAME",
help="fetch theme's data files",
)
# parser.add_argument(
# "--force",
# action="store_true",
# help="overwrite files already present in your project",
# )
# if no args parsed, set --help
return parser.parse_args(None if sys.argv[1:] else ["--help"])
def _get_themes():
return [theme for theme in PELICAN_THEMES_DIR.iterdir() if theme.is_dir()]
def _get_compatible_themes(themes):
return [theme for theme in themes if _is_compatible(theme)]
def _is_compatible(theme):
return theme.joinpath(SRC_DATA_DIR).exists()
def _fetch_files(theme):
try:
shutil.copytree(
theme.joinpath(SRC_DATA_DIR), Path.cwd().joinpath(DEST_DATA_DIR)
)
except FileExistsError:
_err(
f"Cannot copy '{theme.name}' files, "
f"directory '{DEST_DATA_DIR}' already exists.",
die=2,
)
else:
print(f"'{theme.name}' files successfully fetched.")
def main():
"""Main function, called by entrypoint"""
args = _parse_args()
if args.list:
for theme in _get_compatible_themes(_get_themes()):
print(f"{theme.name}")
sys.exit(0)
if args.fetch:
theme = PELICAN_THEMES_DIR.joinpath(args.fetch)
if theme.exists():
if _is_compatible(theme):
_fetch_files(theme)
sys.exit(0)
else:
_err(f"'{args.fetch}' is not a compatible theme.", die=2)
else:
_err(f"'{args.fetch}' is not an existing theme.", die=2)

@ -0,0 +1,38 @@
from pelican import signals
import os
from PIL import Image, ExifTags
# the images are copied to output direction because it has been added as:
# STATIC_PATHS = ['gallery']
def setup_gallery(generator):
GALLERY = []
# TODO: look at content settings to generate gallery_path
IN_GALLERY_PATH = 'content/gallery/'
OUT_GALLERY_PATH = '/gallery/'
for filename in os.listdir(IN_GALLERY_PATH):
img_data = {}
img_data['src'] = OUT_GALLERY_PATH + filename
img = Image.open(IN_GALLERY_PATH + filename)
exif = {
ExifTags.TAGS[k]: v
for k, v in img._getexif().items()
if k in ExifTags.TAGS
}
img_data['time'] = exif['DateTimeOriginal'].split(" ")[1]
GALLERY.append(img_data)
GALLERY = sorted(GALLERY, key=lambda item: item['time'])
print("GALLERY plugin: parsed src and exifs for {n} image in {f}".format(n = len(GALLERY), f = IN_GALLERY_PATH))
# adding it to the pelican context
generator.context['GALLERY'] = GALLERY
def register():
signals.static_generator_finalized.connect(setup_gallery)
# signals.page_generator_write_page.connect(setup_gallery)

@ -0,0 +1 @@
from .image_process import * # NOQA

@ -0,0 +1,730 @@
"""
Image Process
=============
This plugin process images according to their class attribute.
"""
import codecs
import collections
import copy
import functools
import html
import logging
import os.path
import posixpath
import re
import shutil
import subprocess
import sys
from PIL import Image, ImageFilter, UnidentifiedImageError
from bs4 import BeautifulSoup
import six
from six.moves.urllib_parse import unquote, urlparse
from six.moves.urllib_request import pathname2url, url2pathname
from pelican import __version__ as pelican_version
from pelican import signals
log = logging.getLogger(__name__)
IMAGE_PROCESS_REGEX = re.compile("image-process-[-a-zA-Z0-9_]+")
PELICAN_MAJOR_VERSION = int(pelican_version.split(".")[0])
Path = collections.namedtuple("Path", ["base_url", "source", "base_path", "filename"])
# A lot of inspiration from pyexiftool (https://github.com/smarnach/pyexiftool)
class ExifTool(object):
errors = "strict"
sentinel = b"{ready}"
block_size = 4096
_instance = None
@staticmethod
def start_exiftool():
if shutil.which("exiftool") is None:
log.warning(
"[image_process] EXIF tags will not be copied because "
"the exiftool program could not be found. "
"Please install exiftool and make sure it is in your path."
)
else:
ExifTool._instance = ExifTool()
@staticmethod
def copy_tags(src, dst):
if ExifTool._instance is not None:
ExifTool._instance._copy_tags(src, dst)
@staticmethod
def stop_exiftool():
ExifTool._instance = None
def __init__(self):
self.encoding = sys.getfilesystemencoding()
if self.encoding != "mbcs":
try:
codecs.lookup_error("surrogateescape")
except LookupError:
pass
with open(os.devnull, "w") as devnull:
self.process = subprocess.Popen(
[
"exiftool",
"-stay_open",
"True",
"-@",
"-",
"-common_args",
"-G",
"-n",
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=devnull,
)
def __del__(self):
if self.process is not None:
self.process.terminate()
def _copy_tags(self, src, dst):
params = (
b"-TagsFromFile",
src.encode(self.encoding, ExifTool.errors),
b'"-all:all>all:all"',
dst.encode(self.encoding, ExifTool.errors),
)
self._send_command(params)
params = (b"-delete_original!", dst.encode(self.encoding, ExifTool.errors))
self._send_command(params)
def _send_command(self, params):
self.process.stdin.write(b"\n".join(params + (b"-j\n", b"-execute\n")))
self.process.stdin.flush()
output = b""
fd = self.process.stdout.fileno()
while not output.strip().endswith(ExifTool.sentinel):
output += os.read(fd, ExifTool.block_size)
exiftool_result = output.strip()[: -len(ExifTool.sentinel)]
log.debug(
"[image_process] exiftool result: {}".format(
exiftool_result.decode("utf-8")
)
)
def convert_box(image, top, left, right, bottom):
"""Convert box coordinates strings to integer.
t, l, r, b (top, left, right, bottom) must be strings specifying
either a number or a percentage.
"""
bbox = image.getbbox()
img_width = bbox[2] - bbox[0]
img_height = bbox[3] - bbox[1]
if top[-1] == "%":
top = img_height * float(top[:-1]) / 100.0
else:
top = float(top)
if left[-1] == "%":
left = img_width * float(left[:-1]) / 100.0
else:
left = float(left)
if right[-1] == "%":
right = img_width * float(right[:-1]) / 100.0
else:
right = float(right)
if bottom[-1] == "%":
bottom = img_height * float(bottom[:-1]) / 100.0
else:
bottom = float(bottom)
return (top, left, right, bottom)
def crop(i, left, top, right, bottom):
"""Crop image i to the box (left, top)-(right, bottom).
left, top, right, bottom must be strings specifying
either a number or a percentage.
"""
top, left, right, bottom = convert_box(i, top, left, right, bottom)
return i.crop((int(left), int(top), int(right), int(bottom)))
def resize(i, w, h):
"""Resize the image to the dimension specified.
w, h (width, height) must be strings specifying either a number
or a percentage.
"""
_, _, w, h = convert_box(i, "0", "0", w, h)
if i.mode == "P":
i = i.convert("RGBA")
elif i.mode == "1":
i = i.convert("L")
return i.resize((int(w), int(h)), Image.LANCZOS)
def scale(i, w, h, upscale, inside):
"""Resize the image to the dimension specified, keeping the aspect
ratio.
w, h (width, height) must be strings specifying either a number
or a percentage, or "None" to ignore this constraint.
If upscale is True, upscaling is allowed.
If inside is True, the resulting image will not be larger than the
dimensions specified, else it will not be smaller.
"""
bbox = i.getbbox()
iw = bbox[2] - bbox[0]
ih = bbox[3] - bbox[1]
if w == "None":
w = 1.0
elif w[-1] == "%":
w = float(w[:-1]) / 100.0
else:
w = float(w) / iw
if h == "None":
h = 1.0
elif h[-1] == "%":
h = float(h[:-1]) / 100.0
else:
h = float(h) / ih
if inside:
scale = min(w, h)
else:
scale = max(w, h)
if upscale in [0, "0", "False", False]:
scale = min(scale, 1.0)
if i.mode == "P":
i = i.convert("RGBA")
elif i.mode == "1":
i = i.convert("L")
return i.resize((int(scale * iw), int(scale * ih)), Image.LANCZOS)
def rotate(i, degrees):
if i.mode == "P":
i = i.convert("RGBA")
elif i.mode == "1":
i = i.convert("L")
# rotate does not support the LANCZOS filter (Pillow 2.7.0).
return i.rotate(int(degrees), Image.BICUBIC, True)
def apply_filter(i, f):
if i.mode == "P":
i = i.convert("RGBA")
elif i.mode == "1":
i = i.convert("L")
return i.filter(f)
basic_ops = {
"crop": crop,
"flip_horizontal": lambda i: i.transpose(Image.FLIP_LEFT_RIGHT),
"flip_vertical": lambda i: i.transpose(Image.FLIP_TOP_BOTTOM),
"grayscale": lambda i: i.convert("L"),
"resize": resize,
"rotate": rotate,
"scale_in": functools.partial(scale, inside=True),
"scale_out": functools.partial(scale, inside=False),
"blur": functools.partial(apply_filter, f=ImageFilter.BLUR),
"contour": functools.partial(apply_filter, f=ImageFilter.CONTOUR),
"detail": functools.partial(apply_filter, f=ImageFilter.DETAIL),
"edge_enhance": functools.partial(apply_filter, f=ImageFilter.EDGE_ENHANCE),
"edge_enhance_more": functools.partial(
apply_filter, f=ImageFilter.EDGE_ENHANCE_MORE
),
"emboss": functools.partial(apply_filter, f=ImageFilter.EMBOSS),
"find_edges": functools.partial(apply_filter, f=ImageFilter.FIND_EDGES),
"smooth": functools.partial(apply_filter, f=ImageFilter.SMOOTH),
"smooth_more": functools.partial(apply_filter, f=ImageFilter.SMOOTH_MORE),
"sharpen": functools.partial(apply_filter, f=ImageFilter.SHARPEN),
}
def harvest_images(path, context):
log.debug("[image_process] harvesting %r", path)
# Set default value for 'IMAGE_PROCESS_DIR'.
if "IMAGE_PROCESS_DIR" not in context:
context["IMAGE_PROCESS_DIR"] = "derivatives"
# Set default value for 'IMAGE_PROCESS_ENCODING'
if "IMAGE_PROCESS_ENCODING" not in context:
context["IMAGE_PROCESS_ENCODING"] = "utf-8"
# Set default value for 'IMAGE_PROCESS_COPY_EXIF_TAGS'
if "IMAGE_PROCESS_COPY_EXIF_TAGS" not in context:
context["IMAGE_PROCESS_COPY_EXIF_TAGS"] = False
with open(path, "r+", encoding=context["IMAGE_PROCESS_ENCODING"]) as f:
res = harvest_images_in_fragment(f, context)
f.seek(0)
f.truncate()
f.write(res)
def harvest_feed_images(path, context, feed):
# Set default value for 'IMAGE_PROCESS_DIR'.
if "IMAGE_PROCESS_DIR" not in context:
context["IMAGE_PROCESS_DIR"] = "derivatives"
# Set default value for 'IMAGE_PROCESS_ENCODING'
if "IMAGE_PROCESS_ENCODING" not in context:
context["IMAGE_PROCESS_ENCODING"] = "utf-8"
# Set default value for 'IMAGE_PROCESS_COPY_EXIF_TAGS'
if "IMAGE_PROCESS_COPY_EXIF_TAGS" not in context:
context["IMAGE_PROCESS_COPY_EXIF_TAGS"] = False
with open(path, "r+", encoding=context["IMAGE_PROCESS_ENCODING"]) as f:
soup = BeautifulSoup(f, "xml")
for content in soup.find_all("content"):
if content["type"] != "html":
continue
doc = html.unescape(content.string)
res = harvest_images_in_fragment(doc, context)
content.string = res
f.seek(0)
f.truncate()
f.write(str(soup))
def harvest_images_in_fragment(fragment, settings):
parser = settings.get("IMAGE_PROCESS_PARSER", "html.parser")
soup = BeautifulSoup(fragment, parser)
copy_exif_tags = settings.get("IMAGE_PROCESS_COPY_EXIF_TAGS", False)
if copy_exif_tags:
ExifTool.start_exiftool()
for img in soup.find_all("img", class_=IMAGE_PROCESS_REGEX):
for c in img["class"]:
if c.startswith("image-process-"):
derivative = c[14:]
break
else:
continue
try:
d = settings["IMAGE_PROCESS"][derivative]
except KeyError:
raise RuntimeError("Derivative %s undefined." % derivative)
if isinstance(d, list):
# Single source image specification.
process_img_tag(img, settings, derivative)
elif not isinstance(d, dict):
raise RuntimeError(
"Derivative %s definition not handled"
"(must be list or dict)" % (derivative)
)
elif "type" not in d:
raise RuntimeError('"type" is mandatory for %s.' % derivative)
elif d["type"] == "image":
# Single source image specification.
process_img_tag(img, settings, derivative)
elif d["type"] == "responsive-image" and "srcset" not in img.attrs:
# srcset image specification.
build_srcset(img, settings, derivative)
elif d["type"] == "picture":
# Multiple source (picture) specification.
group = img.find_parent()
if group.name == "div":
convert_div_to_picture_tag(soup, img, group, settings, derivative)
elif group.name == "picture":
process_picture(soup, img, group, settings, derivative)
ExifTool.stop_exiftool()
return str(soup)
def compute_paths(img, settings, derivative):
process_dir = settings["IMAGE_PROCESS_DIR"]
img_src = urlparse(img["src"])
img_src_path = url2pathname(img_src.path.lstrip("/"))
img_src_dirname, filename = os.path.split(img_src_path)
derivative_path = os.path.join(process_dir, derivative)
# urljoin truncates leading ../ elements
base_url = posixpath.join(
posixpath.dirname(img["src"]), pathname2url(derivative_path)
)
if PELICAN_MAJOR_VERSION < 4:
file_paths = settings["filenames"]
else:
file_paths = settings["static_content"]
for f, contobj in file_paths.items():
save_as = contobj.get_url_setting("save_as")
# save_as can be set to empty string, which would match everything
if save_as and img_src_path.endswith(save_as):
source = contobj.source_path
base_path = os.path.join(
contobj.settings["OUTPUT_PATH"],
os.path.dirname(contobj.get_url_setting("save_as")),
process_dir,
derivative,
)
break
else:
if "SITEURL" in settings:
site_url = urlparse(settings["SITEURL"])
site_url_path = url2pathname(site_url.path[1:])
else:
# if SITEURL is undefined, don't break!
site_url_path = None
if site_url_path:
src_path = img_src_path.partition(site_url_path)[2].lstrip("/")
else:
src_path = img_src_path.lstrip("/")
source = os.path.join(settings["PATH"], src_path)
base_path = os.path.join(
settings["OUTPUT_PATH"], os.path.dirname(src_path), derivative_path
)
return Path(base_url, source, base_path, filename)
def process_img_tag(img, settings, derivative):
path = compute_paths(img, settings, derivative)
if not is_img_identifiable(path.source):
log.warn(
"[image_process] Skipping image %s that could not be identified by Pillow",
path.source,
)
return
process = settings["IMAGE_PROCESS"][derivative]
img["src"] = posixpath.join(path.base_url, path.filename)
destination = os.path.join(path.base_path, path.filename)
if not isinstance(process, list):
process = process["ops"]
process_image((path.source, destination, process), settings)
def is_img_identifiable(img_filepath):
try:
Image.open(img_filepath)
return True
except (FileNotFoundError, UnidentifiedImageError):
return False
def build_srcset(img, settings, derivative):
path = compute_paths(img, settings, derivative)
if not is_img_identifiable(path.source):
log.warn(
"[image_process] Skipping image %s that could not be identified by Pillow",
path.source,
)
return
process = settings["IMAGE_PROCESS"][derivative]
default = process["default"]
if isinstance(default, six.string_types):
breakpoints = {i for i, _ in process["srcset"]}
if default not in breakpoints:
log.error(
'[image_process] srcset "%s" does not define default "%s"',
derivative,
default,
)
default_name = default
elif isinstance(default, list):
default_name = "default"
destination = os.path.join(path.base_path, default_name, path.filename)
process_image((path.source, destination, default), settings)
img["src"] = posixpath.join(path.base_url, default_name, path.filename)
if "sizes" in process:
img["sizes"] = process["sizes"]
srcset = []
for src in process["srcset"]:
file_path = posixpath.join(path.base_url, src[0], path.filename)
srcset.append("%s %s" % (file_path, src[0]))
destination = os.path.join(path.base_path, src[0], path.filename)
process_image((path.source, destination, src[1]), settings)
if len(srcset) > 0:
img["srcset"] = ", ".join(srcset)
def convert_div_to_picture_tag(soup, img, group, settings, derivative):
"""
Convert a div containing multiple images to a picture.
"""
process_dir = settings["IMAGE_PROCESS_DIR"]
# Compile sources URL. Special source "default" uses the main
# image URL. Other sources use the img with classes
# [source['name'], 'image-process']. We also remove the img from
# the DOM.
sources = copy.deepcopy(settings["IMAGE_PROCESS"][derivative]["sources"])
for s in sources:
if s["name"] == "default":
s["url"] = img["src"]
else:
candidates = group.find_all("img", class_=s["name"])
for candidate in candidates:
if "image-process" in candidate["class"]:
s["url"] = candidate["src"]
candidate.decompose()
break
url_path, s["filename"] = os.path.split(s["url"])
s["base_url"] = os.path.join(url_path, process_dir, derivative)
s["base_path"] = os.path.join(settings["OUTPUT_PATH"], s["base_url"][1:])
# If default is not None, change default img source to the image
# derivative referenced.
default = settings["IMAGE_PROCESS"][derivative]["default"]
if default is not None:
default_source_name = default[0]
default_source = None
for s in sources:
if s["name"] == default_source_name:
default_source = s
break
if default_source is None:
raise RuntimeError(
'No source matching "%s", referenced in default setting.',
(default_source_name,),
)
if isinstance(default[1], six.string_types):
default_item_name = default[1]
elif isinstance(default[1], list):
default_item_name = "default"
source = os.path.join(settings["PATH"], default_source["url"][1:])
destination = os.path.join(
s["base_path"],
default_source_name,
default_item_name,
default_source["filename"],
)
process_image((source, destination, default[1]), settings)
# Change img src to url of default processed image.
img["src"] = os.path.join(
s["base_url"],
default_source_name,
default_item_name,
default_source["filename"],
)
# Create picture tag.
picture_tag = soup.new_tag("picture")
for s in sources:
# Create new <source>
source_attrs = {k: s[k] for k in s if k in ["media", "sizes"]}
source_tag = soup.new_tag("source", **source_attrs)
srcset = []
for src in s["srcset"]:
srcset.append(
"%s %s"
% (
os.path.join(s["base_url"], s["name"], src[0], s["filename"]),
src[0],
)
)
source = os.path.join(settings["PATH"], s["url"][1:])
destination = os.path.join(s["base_path"], s["name"], src[0], s["filename"])
process_image((source, destination, src[1]), settings)
if len(srcset) > 0:
source_tag["srcset"] = ", ".join(srcset)
picture_tag.append(source_tag)
# Wrap img with <picture>
img.wrap(picture_tag)
def process_picture(soup, img, group, settings, derivative):
"""
Convert a simplified picture to a full HTML picture:
<picture>
<source class="source-1" src="image1.jpg"></source>
<source class="source-2" src="image2.jpg"></source>
<img class="image-process-picture" src="image3.jpg"></img>
</picture>
to
<picture>
<source srcset="...image1.jpg..." media="..." sizes="..."></source>
<source srcset="...image2.jpg..."></source>
<source srcset="...image3.jpg..." media="..." sizes="..."></source>
<img src=".../image3.jpg"></img>
</picture>
"""
process_dir = settings["IMAGE_PROCESS_DIR"]
process = settings["IMAGE_PROCESS"][derivative]
# Compile sources URL. Special source "default" uses the main
# image URL. Other sources use the <source> with classes
# source['name']. We also remove the <source>s from the DOM.
sources = copy.deepcopy(process["sources"])
for s in sources:
if s["name"] == "default":
s["url"] = img["src"]
source_attrs = {k: s[k] for k in s if k in ["media", "sizes"]}
s["element"] = soup.new_tag("source", **source_attrs)
else:
s["element"] = group.find("source", class_=s["name"]).extract()
s["url"] = s["element"]["src"]
del s["element"]["src"]
del s["element"]["class"]
url_path, s["filename"] = os.path.split(s["url"])
s["base_url"] = posixpath.join(url_path, process_dir, derivative)
s["base_path"] = os.path.join(settings["OUTPUT_PATH"], s["base_url"][1:])
# If default is not None, change default img source to the image
# derivative referenced.
default = process["default"]
if default is not None:
default_source_name = default[0]
default_source = None
for s in sources:
if s["name"] == default_source_name:
default_source = s
break
if default_source is None:
raise RuntimeError(
'No source matching "%s", referenced in default setting.',
(default_source_name,),
)
if isinstance(default[1], six.string_types):
default_item_name = default[1]
elif isinstance(default[1], list):
default_item_name = "default"
source = os.path.join(settings["PATH"], default_source["url"][1:])
destination = os.path.join(
s["base_path"],
default_source_name,
default_item_name,
default_source["filename"],
)
process_image((source, destination, default[1]), settings)
# Change img src to url of default processed image.
img["src"] = posixpath.join(
s["base_url"],
default_source_name,
default_item_name,
default_source["filename"],
)
# Generate srcsets and put back <source>s in <picture>.
for s in sources:
srcset = []
for src in s["srcset"]:
srcset.append(
"%s %s"
% (
posixpath.join(s["base_url"], s["name"], src[0], s["filename"]),
src[0],
)
)
source = os.path.join(settings["PATH"], s["url"][1:])
destination = os.path.join(s["base_path"], s["name"], src[0], s["filename"])
process_image((source, destination, src[1]), settings)
if len(srcset) > 0:
# Append source elements to the picture in the same order
# as they are found in
# settings['IMAGE_PROCESS'][derivative]['sources'].
s["element"]["srcset"] = ", ".join(srcset)
img.insert_before(s["element"])
def process_image(image, settings):
# Set default value for 'IMAGE_PROCESS_FORCE'.
if "IMAGE_PROCESS_FORCE" not in settings:
settings["IMAGE_PROCESS_FORCE"] = False
# remove URL encoding to get to physical filenames
image = list(image)
image[0] = unquote(image[0])
image[1] = unquote(image[1])
# image[2] is the transformation
log.debug("[image_process] {} -> {}".format(image[0], image[1]))
os.makedirs(os.path.dirname(image[1]), exist_ok=True)
# If original image is older than existing derivative, skip
# processing to save time, unless user explicitly forced
# image generation.
if (
settings["IMAGE_PROCESS_FORCE"]
or not os.path.exists(image[1])
or os.path.getmtime(image[0]) > os.path.getmtime(image[1])
):
i = Image.open(image[0])
for step in image[2]:
if hasattr(step, "__call__"):
i = step(i)
else:
elems = step.split(" ")
i = basic_ops[elems[0]](i, *(elems[1:]))
# `save_all=True` will allow saving multi-page (aka animated) GIF's
# however, turning it on seems to break PNG support, and doesn't seem
# to work on GIF's either...
i.save(image[1], progressive=True)
ExifTool.copy_tags(image[0], image[1])
def register():
signals.content_written.connect(harvest_images)
signals.feed_written.connect(harvest_feed_images)

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 KiB

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"/>

After

Width:  |  Height:  |  Size: 42 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save