publishing the project
This commit is contained in:
commit
a8a511b789
8 changed files with 283 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
Compass 9.ttf
|
||||||
|
image.png
|
34
README.md
Normal file
34
README.md
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
# Automated Infodumping
|
||||||
|
|
||||||
|
I really enjoy the fact that *Tao Te Ching* by Lao Tzu exists. The first translation I have ever read was Carol Deppe's. It's simple, made with some artistic liberty to read more easily, so it was a great intro.
|
||||||
|
|
||||||
|
I wanted to infodump about it to [snow](https://cofe.rocks/users/snow) but that's a lot of content to speak or type, even for me. But she did some computer magic to a kindle and exposed `http://kindle.sn0w.cx/data` which accepts image data in `POST` requests and displays them on that kindle (somewhere in her house).
|
||||||
|
|
||||||
|
Then I found out about this beautiful font [Compass](https://somepx.itch.io/pixel-font-compass) by somepx.
|
||||||
|
|
||||||
|
And now I connected those two dots into the inspiration for this quick project.
|
||||||
|
|
||||||
|
![The Tao that can be told is not the eternal Tao. The name that can be named is not the eternal name. Unnamable is the essence. Naming is the beginning of ten thousand particular things. Named are the manifestations. Nameless is the mystery.](./first_verse.png)
|
||||||
|
|
||||||
|
|
||||||
|
![photo of the kindle displaying the same quote image as above](./kindle_photo.png)
|
||||||
|
|
||||||
|
## The code
|
||||||
|
|
||||||
|
This is very spaghetti code - don't use it as a good example of programatic image generation. I was writing it as I was experimenting and silly reasons don't justify refactoring time. It works!
|
||||||
|
|
||||||
|
The code runs every day but it only generates and sends an image every 3 days. It takes the next quote that it hasn't shown yet, finds the right font size and line breaks in a very inefficient way, adds the attribution for the translator of the book and the font author, and `POST`s it to snow's kindle.
|
||||||
|
|
||||||
|
## Result
|
||||||
|
|
||||||
|
Now all my infodumping about Tao Te Ching will happen automatically! It will happen over *\*quick math\** about a year (107 quotes, once every 3 days).
|
||||||
|
|
||||||
|
I love the old-school fantasy look of the text and I find it satisfying that it displays literal ancient wisdom.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
### Font
|
||||||
|
[Compass](https://somepx.itch.io/pixel-font-compass) by somepx. I bought it, so I can't include it here. You can buy it and copy the file to the directory where you run the code or you can use any other font and it *should* work (maybe with some tweaks).
|
||||||
|
|
||||||
|
### Tao Te Ching
|
||||||
|
You can download the pdf of the book from the author's website https://www.caroldeppe.com/. The PDF also mentions it's okay to share the PDF so I included it as well as the `txt` version of the "Master/she" section for the Python code.
|
BIN
Tao Te Ching.pdf
Normal file
BIN
Tao Te Ching.pdf
Normal file
Binary file not shown.
107
Tao Te Ching.txt
Normal file
107
Tao Te Ching.txt
Normal file
|
@ -0,0 +1,107 @@
|
||||||
|
The Tao that can be told is not the eternal Tao. The name that can be named is not the eternal name. Unnamable is the essence. Naming is the beginning of ten thousand particular things. Named are the manifestations. Nameless is the mystery.
|
||||||
|
Whenever there is beauty there is ugliness. Whenever there is good there is bad. Long and short complete each other. High and low support each other. Difficult and easy need each other. Sound and silence fulfill each other. Front and back follow each other. Form and space shape each other. Life and death give birth to each other. Manifestations and Mystery come from the same source.
|
||||||
|
The Master is one with the Tao. She acts without forcing. She teaches by showing. Things come and she lets them come. Things go and she lets them go. She gives birth without possessing, achieves without expecting, creates without taking credit, works without needing praise. She completes her work, then forgets it. Her work lasts forever.
|
||||||
|
The Tao is like a fertile valley, filled with creativity, Gateway of the Female, roots of Heaven and Earth.
|
||||||
|
The Tao is like a well, empty but inexhaustible—dark, enduring, deep—ancestor of ten thousand things. However much you use it, you never have to fill it. However much you use it, you never use it up.
|
||||||
|
Edge without sharpness, knot without tangle, hole without emptiness, door without opening. Soft glare. Clear fog. Submerged, indistinct, motherless, older than the gods.
|
||||||
|
Thirty spokes, a rim, and a hub make a wheel. The hole in the center moves the cart. Clay molds into a pot. The emptiness inside holds the food. Roof, walls, and floor frame a house. The space within is where we live. Existence gives the form. Nonexistence gives the meaning.
|
||||||
|
Look for it and you can’t see it. Listen for it and you can’t hear it. Reach for it and you can’t touch it. Grasp at it and you can’t hold it. Approach it and it has no beginning. Follow it and it has no end.
|
||||||
|
When the superior hear about the Tao, they immediately endeavor to practice it. When the average hear about the Tao, they try it part way. When the lesser hear about the Tao, they laugh. That’s why they are lesser, and the Tao is the Tao.
|
||||||
|
Seek, and with this you will find. If you have committed wrongs, with this you will escape.
|
||||||
|
For the good, their treasure. For the bad, their refuge.
|
||||||
|
The Tao is impartial. It gives birth to both good and evil. The Master is impartial. She uses whatever life sends her.
|
||||||
|
Heaven covers. Earth supports. Heaven and Earth endure.
|
||||||
|
In living, honor the land. In thinking, be deep. In speaking be truthful. In working, be skillful. In dealing with others, be compassionate. In giving, be generous. In ruling be fair. In acting, be timely.
|
||||||
|
The ten thousand things are female on one side and male on the other. Using both creates vitality. Balancing both creates harmony.
|
||||||
|
Know the male but hold to the female. Know the white but hold to the black. Know the peaks but hold to the valleys. Know complexity but hold to simplicity. Know sound but hold to silence. Know action but hold to stillness. Know knowledge but hold to innocence. Know the manifestations but hold to the mystery.
|
||||||
|
Activity counters cold. Tranquility counters heat.
|
||||||
|
The Tao is the Great Mother. The ten thousand things are all her children. Know the Mother and you will know the children. Know the children and you will know the Mother.
|
||||||
|
First we name. Then we describe. Then we compare. Then we set one first, another last. As soon as we start to name it’s time to stop.
|
||||||
|
Fill yourself with utmost emptiness. Embrace internal tranquility. The ten thousand things, see how they arise and flow around you—each one coming into being, growing, adapting, changing, fulfilling, then returning to the source—as you sit in stillness in the center, watching.
|
||||||
|
Be aware, observe, notice. Appreciate the small. Find flavor in the delicate.
|
||||||
|
Live wood is soft and tender. Dead wood is hard and strong. The live leaf is supple. The dead leaf is brittle. The army that isn’t flexible never wins a battle. The tree that survives the storm is the one that bends in the wind.
|
||||||
|
Yield and prevail. If you can bend, you can be preserved unbroken. If you can flex, you can be kept straight. If you can be emptied, you can be filled. If you can be worn out, you can be renewed. Those with little can receive much. Those with much can be confused.
|
||||||
|
The Tao is like water. Water takes the lowest way. It flows around obstacles. It has no projections, but it penetrates that which has no crevices. It’s the softest of all things, but it grinds rock. It resists nothing, but is irresistible. It asks for nothing, but nourishes everything. It strives for nothing, but transforms everything.
|
||||||
|
One who is one with the Tao is like a newborn boy-child. His body is soft and pliant but his grasp is strong. He doesn’t yet know the union of male and female, but his organ stands up. He can scream all day without getting hoarse or sleep utterly peacefully. He does just what he should be doing at each moment. He is completely natural.
|
||||||
|
The Master is cautious, like one who fords a river in winter—careful, like one restrained in speaking—formal, like a host— courteous, like a guest—generous, like a fertile valley—plain, like uncarved wood— natural, like a tree in the wilderness—calm and serene, like a still pool of deep water.
|
||||||
|
Be detached. Work with joy, without caring for the achievement. Travel with joy, without focusing on the destination.
|
||||||
|
On disaster good fortune perches. Beneath good fortune disaster crouches. Straight becomes crooked, which becomes straight again. Good gives rise to evil, which gives rise to good again. There is no beginning or ending.
|
||||||
|
The bright way may seem dark. The straight way may seem crooked. The smooth way may seem rough. The way forward may seem to go backward. True love may seem heartless. True integrity may seem dishonest. True fullness may seem empty. And even the eternal may seem to change.
|
||||||
|
Sincere words may not be beautiful. Beautiful words may not be sincere. The wise may not be learned. The learned may not be wise. The good may not be rich. The rich may not be good. Those who know may not speak. Those who speak may not know.
|
||||||
|
Success is as treacherous as failure. Praise is as useless as blame. Fortune, fame, and favor are as dangerous as disgrace. High status and position can bring you great affliction.
|
||||||
|
You can lose by gaining. You can gain by losing.
|
||||||
|
Trapped in desires, you see only your desires. Trapped in desires, you see surfaces. Free from desires, you see the subtleties. Free from desires, you experience the mystery.
|
||||||
|
Look to achievement for satisfaction and you will never be satisfied. Look to riches for contentment and you will never be content. Look to possessions for happiness and you will never be happy. Look to position for security and you will never be secure. Appreciate what you have. Rejoice in how things are. You lack nothing when you realize—there is nothing lacking.
|
||||||
|
The Master practices non-knowing. She knows that she does not know what is good and what is evil. So she cleanses her mind of desire for particular ends, and accepts everything, and lets everything happen, and takes joy in everything, and uses everything that comes her way.
|
||||||
|
To know that you know not is sanity. To know not that you know not is sickness. The Master is her own healer. She cures herself of false knowing.
|
||||||
|
The Master heals the people. She teaches them non-knowing. When people think they know, they can’t be guided. When people know that they don’t know, they can find their own way.
|
||||||
|
The Master desires not to desire. She values what is everywhere. She learns what to unlearn. She returns to what the masses pass by.
|
||||||
|
The Master puts herself last and is first, puts herself below and is above, gives up personal desires and finds her desires all satisfied, gives up self-interest and finds her interests realized, let’s go of everything and is one with everything, empties herself completely and is completely fulfilled.
|
||||||
|
In seeking knowledge, day by day something is added. In following Tao, day by day something is dropped. Day by day you do less and less deliberately. Day by day you don’t do more and more. You do less and less and don’t do more and more, until everything happens spontaneously. Then you act without acting, and do without doing, and achieve without forcing. And nothing is done. And nothing is left undone.
|
||||||
|
Muddy water, when still, gradually becomes clear. Be still. Let your mud settle and your mind clear. Wait quietly until the right action comes naturally.
|
||||||
|
Grasp at something and lose it. Act with purpose and defeat the purpose.
|
||||||
|
The soldier who goes out ready to die comes back with life and victory. The soldier who goes out caring mostly for living dies and is forgotten.
|
||||||
|
Heaven favors—who knows what or why? Bravery may lead to death and loss. Caution may lead to life and victory. Without fighting you can be good at winning. Without speaking you can be good at responding. Without deliberateness you can be good at planning. No one summons the Tao. It comes on its own. Heaven’s net is vast and cast wide, and nothing slips through.
|
||||||
|
The Master doesn’t act on the ten thousand things. She simply helps them be themselves. The Master doesn’t try to change the people. She simply shows them who they are. She leads them back to where they came from. She leads them back to what they have always known.
|
||||||
|
The Master doesn’t speak. She acts. The Master doesn’t teach. She shows. When the Master rules, the people hardly know she is there. When the Master’s work is done, the people say, “Look! We did this! All by ourselves!”
|
||||||
|
The Master is impartial. She is good to the good. She is good to the bad. Such is true good.
|
||||||
|
The good teach. The bad are the raw material. Cherish the teacher and the raw material.
|
||||||
|
Insincere words can be bought and sold. Empty deeds can be used as gifts. Things we see as bad—should they ever be rejected? People we see as bad—should they ever be abandoned?
|
||||||
|
The Master knows the tally, but doesn’t call for the rewards or punishments. Those with virtue can do the accounting. Those without virtue collect the taxes.
|
||||||
|
The Master accepts everyone as children of the Tao, and treats everyone with compassion, generosity, and understanding.
|
||||||
|
The world says I am great, but strange. If I weren’t strange, I couldn’t be great. If I were like everyone else, I would be insignificant.
|
||||||
|
Something there is that formed out of Chaos—pure and deep and still—standing alone, unchanging—Mother of Heaven and Earth. I do not know its name. I only ‘call’ it “Tao.”
|
||||||
|
I have three treasures I hold and cherish: compassion, frugality, and not needing to be ahead of all under heaven. Compassion gives me courage. Frugality allows generosity. Not needing to be ahead lets me lead the people.
|
||||||
|
Other people are noisy and exuberant. I am silent—like something that has not yet given any sign—like a baby who has not yet smiled. Other people have many possessions. I have nothing. Other people know where they’re going and what they’re doing. I am ignorant. Other people judge things and make many fine distinctions. I find everything subtle and complex. Other people act with purpose. I drift and float. Formless am I—like the ocean—shapeless, unmoving, unresting. I suck from the breast of the Mother.
|
||||||
|
Heaven covers everything. Can you be as generous? Earth supports everything. Can you be as tolerant?
|
||||||
|
Can you play the part of the female? Can you accept, allow, adapt, flex, bend, change? Can you use everything that comes your way?
|
||||||
|
Can you be natural and spontaneous? Can you be like a new-born babe?
|
||||||
|
Can you love the people? Can you teach and lead and serve them? Can you love them without trying to change them? Can you lead them and leave them free?
|
||||||
|
Can you embrace the One? Can you cleanse and polish and purify the bright mirror of your soul? Can you concentrate and focus your breath and energy? Can you step outside yourself and understand all within the four reaches?
|
||||||
|
Give birth without owning. Love without possessing. Teach without making dependent. Lead without trying to control. Act by helping things happen naturally. Guide by helping things grow naturally. Empty yourself, and let the Tao fill you and move through you and use you as part of the pattern.
|
||||||
|
The Tao takes no action. Yet everything happens. If leaders could hold to it, the world would transform spontaneously. If, after the transformation, some wanted to take action, I would calm them with nameless simplicity.
|
||||||
|
If I had just the smallest speck of wisdom, I could walk on the Great Way, and the only fear I would have would be of going astray. The Great Way is straight and smooth and easy to follow. But people delight in the crooked and rough and difficult.
|
||||||
|
My words are easy to understand and easy to put into practice. But few understand, and few put them into practice.
|
||||||
|
If everyone understood, what use would I be? It’s because few understand that I can be of great value.
|
||||||
|
A few will stop to hear about the Tao. Everyone will stop for food or music.
|
||||||
|
The light rests on the heavy. The mountain grows from the valley. The noble is rooted in the common. Clear water floats over mud. The Master knows her roots. She loves, understands, and honors ordinary people.
|
||||||
|
In expression, to be brief is natural. A whirlwind doesn’t last all morning. A cloudburst doesn’t last all day.
|
||||||
|
Boasting and bragging are extra food and unnecessary baggage. They impede traveling on the Way.
|
||||||
|
Self-praise is no praise. When you describe an imaginary carriage, dream as you wish, embellish as you want, enumerate all the features as you will—there is still no carriage.
|
||||||
|
A jade necklace shines brightly, displays itself for everyone, jingles constantly. The Master is not like the jade. She just rumbles occasionally—like a rock.
|
||||||
|
The Master gives herself to others, then is even greater. The Master uses what she has for others, then has even more. The Tao nurtures everything and harms nothing. The Master helps all and hurts none.
|
||||||
|
The Master gives, but she doesn’t give her Self away. The Master serves, but she serves her Self first. The best commander isn’t killed or captured. How could the armies prevail without the commander?
|
||||||
|
The Master travels all day without ever losing sight of her baggage. When she is safely within a walled-in hostel, then she relaxes and transcends all cares.
|
||||||
|
Look for virtue and success, and you find them everywhere. Look for failure and loss, and they constantly befall you.
|
||||||
|
Use the Way as the means, and the end will be one with the Way. Follow the Way and the Way will be straight before you.
|
||||||
|
Too much light causes blindness. Too much sound causes deafness. Too much indulgence in physical pleasures causes distraction and dissipation. Having too many possessions impedes traveling on the Way.
|
||||||
|
The Master holds to the center. She dwells in the substance, not in the surface, in the fruit, not in the flower, in reality, not in appearances, in the essence, not in the ornament.
|
||||||
|
Fill your cup too full and it will spill. Sharpen your knife too much and it will blunt. Acquire too much and you will be unable to protect it. Climb too high and you will be unable to maintain it. Too much pride brings on its own disaster. Too much study leads to exhaustion. More words mean less. Walk too far and you will pass your destination.
|
||||||
|
The skillful carver does little cutting. The skillful traveler leaves few tracks and traces. The skillful binding takes few knots, but does not come undone. The skillful speaker uses few words.
|
||||||
|
The Master is sharp, but doesn’t cut. The Master is pointed, but doesn’t pierce. The Master is straightforward, but not unrestrained. The Master is bright, but doesn’t dazzle.
|
||||||
|
The greatest mistake is desiring too much. The greatest sorrow is not knowing when you have enough. The greatest fault is needing to compete. The greatest defect is not knowing when to stop.
|
||||||
|
Stop trouble before it starts. Make order before there is chaos. Deal with the small before it is large. Deal with the few before they are many. Begin the difficult while it is easy. Approach the great work through a series of small tasks. The largest evergreen grows from a tiny seedling. The journey of a thousand miles starts with a single step.
|
||||||
|
If you rush into action, you may stumble. If you stand on tiptoe you do not stand stable. Failure comes most often near completion. Be as careful at the end as the beginning.
|
||||||
|
One who is one with the Tao acts without acting. One who is less with the Tao acts with purpose. The greatest Self is not selfconscious. The lesser Self is always aware of itself. The greatest integrity is spontaneous. The lesser integrity is deliberate. The greatest virtue is unaware of virtue. The lesser virtue never loses sight of virtue.
|
||||||
|
To know others is knowledge. To know Self is wisdom. To control others shows power. To control Self is to be truly powerful. To know when you have enough is to be rich. To know when to act is to act appropriately. To know when to hold your place is to endure. To live at one with the Tao is to live forever.
|
||||||
|
You can’t get too close to the Master. You can’t shun her. You can’t help her. You can’t harm her. You can’t ennoble her. You can’t debase her. She is already the noblest thing under heaven.
|
||||||
|
The best leader is invisible. The next best is loved and praised. The next is feared. The worst is ridiculed.
|
||||||
|
The best warrior isn’t warlike. The best fighter isn’t aggressive. The best commander avoids combat. The best ruler serves the people.
|
||||||
|
Ruling a large state is like frying a small fish. Cook it too much and you ruin it. Poke at it too much and it falls apart.
|
||||||
|
When government is weak and invisible, people are open and honest. When government is powerful and interfering, people are secretive and devious.
|
||||||
|
Too many taxes and the people starve. Too many rules and regulations and the people chafe and fret. When there is too much reward for success or too little room for succeeding, people will compete desperately. When goods are priced too high or wages too low, people will steal. When they are constantly shown good things they cannot have, people will rebel.
|
||||||
|
When mansions are kept very clean, and rich people wear fine clothes, and carry sharp swords, and gorge themselves on expensive foods, and have luxurious possessions—while the fields of the poor are full of weeds, and in the villages, the granaries are empty—this is thievery! This is not the Way!
|
||||||
|
When the Way is lost, there is virtue. When virtue is lost there is humanity. When humanity is lost there is righteousness. When righteousness is lost, there is propriety. Propriety is the beginning of chaos. When people don’t respond, it rolls up its sleeves and uses force.
|
||||||
|
Killing people in place of the master executioner is like cutting wood in place of the head carpenter. Cut wood in place of the head carpenter, and you are likely to cut your own hands.
|
||||||
|
When a nation loses the Way, weapons abound, and warhorses are stabled in the suburbs.
|
||||||
|
Weapons are instruments of ill omen. They should never be made into things of beauty. To worship weapons is to glorify in killing.
|
||||||
|
Don’t deal in violence. Violence rebounds. Don’t glorify in war. Use weapons only when there is no other choice. After war the famines come. Where armies go, thorns and brambles grow.
|
||||||
|
The world is a sacred vessel. You can’t improve it. Act on it to improve it and you ruin it. Try to control it and you come to ruin.
|
||||||
|
The Way of Heaven is like the flexing of a bow. The high is drawn down. The low is brought up. When the string is pulled, all the parts move.
|
||||||
|
You don’t need to leave home in order to see the world. You don’t have to look out your window in order to find the way. The harder you search the less you find. The farther you go the less you see.
|
||||||
|
The Master sees without looking, finds without searching, and arrives without going anywhere.
|
||||||
|
Build your foundation upon it. What is firmly founded cannot be torn down. Embrace it. What is embraced tightly will be held. Cultivate it in yourself. Nurture it in your family. Practice it in your city. Express it in your state. Spread it throughout the universe. Let it overflow.
|
||||||
|
Square without corners, vessel without walls, soundless tone, formless image—that is the shape of the Tao. Accept, allow, adapt, flex, bend, change—that is the method of the Tao. Create, complete, fulfill, reverse, return, renew—that is the movement of the Tao.
|
||||||
|
Every particular thing is a manifestation of the Tao. The Tao gives rise to all things. The Tao fulfills them. To the Tao they return. That is why everything venerates the Tao. That is why we find the Tao when we look inside ourselves.
|
||||||
|
There is a time for living and a time for dying, a time for planting and a time for reaping, a time for motion and a time for stillness, a time for working and a time for rest.
|
||||||
|
The Tao gives birth to all things, nourishes them, shelters them, cares for them, comforts them, and in the end, receives them back into itself.
|
BIN
first_verse.png
Normal file
BIN
first_verse.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 34 KiB |
140
generate_image.py
Normal file
140
generate_image.py
Normal file
|
@ -0,0 +1,140 @@
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
from datetime import date, timedelta
|
||||||
|
import io
|
||||||
|
import requests
|
||||||
|
|
||||||
|
# Read in the quotes
|
||||||
|
with open('Tao Te Ching.txt', 'r', encoding='utf-8') as f:
|
||||||
|
tao = [line.replace('\ufeff', '').strip() for line in f.readlines()]
|
||||||
|
|
||||||
|
|
||||||
|
# Pick the day to send and pick which quote to send
|
||||||
|
show_new_quote_frequency_days = 3
|
||||||
|
|
||||||
|
start_date = date(2024, 7, 26)
|
||||||
|
today = date.today()
|
||||||
|
yesterday = today - timedelta(days=1)
|
||||||
|
index_today = (today - start_date).days // show_new_quote_frequency_days
|
||||||
|
index_yesterday = (yesterday - start_date).days // show_new_quote_frequency_days
|
||||||
|
if index_today < 0 or not (index_today > index_yesterday):
|
||||||
|
print('not today')
|
||||||
|
exit()
|
||||||
|
|
||||||
|
if index_today >= len(tao):
|
||||||
|
print("we're done")
|
||||||
|
exit()
|
||||||
|
|
||||||
|
verse_index = index_today + 1
|
||||||
|
text = tao[verse_index-1]
|
||||||
|
|
||||||
|
# Generating the image
|
||||||
|
global_scale = 10
|
||||||
|
size = (134*8*global_scale, 181*8*global_scale)
|
||||||
|
margin = int(0.1*size[0])
|
||||||
|
text_box_size = (size[0] - 2*margin, size[1] - 2*margin)
|
||||||
|
|
||||||
|
font_path = "Compass 9.ttf"
|
||||||
|
|
||||||
|
image = Image.new('RGB', size, (0,0,0))
|
||||||
|
draw = ImageDraw.Draw(image)
|
||||||
|
|
||||||
|
fontsize = 40*global_scale
|
||||||
|
font = ImageFont.truetype(font_path, fontsize)
|
||||||
|
|
||||||
|
# Helper functions
|
||||||
|
def get_width(text, font):
|
||||||
|
return get_dims(text, font)[0]
|
||||||
|
|
||||||
|
def get_dims(text, font):
|
||||||
|
lines = text.split('\n')
|
||||||
|
width = 0
|
||||||
|
height = 0
|
||||||
|
for line in lines:
|
||||||
|
box = font.getbbox(line)
|
||||||
|
if box[2] - box[0] > width:
|
||||||
|
width = box[2] - box[0]
|
||||||
|
height += 1.2 * (box[3] - box[1])
|
||||||
|
return width, height
|
||||||
|
|
||||||
|
def get_ratio(text, font):
|
||||||
|
w, h = get_dims(text, font)
|
||||||
|
return w/h
|
||||||
|
|
||||||
|
|
||||||
|
# Finding where to add \n and which font size will fit the kindle screen best
|
||||||
|
words = text.split()
|
||||||
|
print(words)
|
||||||
|
|
||||||
|
current_ratio = None
|
||||||
|
previous_ratio = None
|
||||||
|
goal_ratio = text_box_size[0]/text_box_size[1]
|
||||||
|
wrapped_text = None
|
||||||
|
|
||||||
|
while wrapped_text is None or current_ratio is None or previous_ratio is None or (abs(goal_ratio - current_ratio) < abs(goal_ratio - previous_ratio) and get_dims(wrapped_text, font)[1] < text_box_size[1]):
|
||||||
|
lines = [[]]
|
||||||
|
word_index = 0
|
||||||
|
line_index = 0
|
||||||
|
while word_index < len(words):
|
||||||
|
if get_width(' '.join(lines[line_index]) + ' ' + words[word_index], font) >= text_box_size[0]:
|
||||||
|
break
|
||||||
|
while get_width(' '.join(lines[line_index]) + ' ' + words[word_index], font) < text_box_size[0]:
|
||||||
|
lines[line_index].append(words[word_index])
|
||||||
|
word_index += 1
|
||||||
|
if word_index >= len(words) - 1:
|
||||||
|
break
|
||||||
|
line_index += 1
|
||||||
|
lines.append([])
|
||||||
|
|
||||||
|
wrapped_text = '\n'.join([' '.join(line) for line in lines]).strip()
|
||||||
|
previous_ratio = current_ratio
|
||||||
|
current_ratio = get_ratio(wrapped_text, font)
|
||||||
|
fontsize += global_scale * 10
|
||||||
|
font = ImageFont.truetype(font_path, fontsize)
|
||||||
|
print(goal_ratio, current_ratio, fontsize, text_box_size, get_dims(wrapped_text, font))
|
||||||
|
|
||||||
|
|
||||||
|
# Stepping back the fontsize
|
||||||
|
fontsize -= global_scale * 20
|
||||||
|
font = ImageFont.truetype(font_path, fontsize)
|
||||||
|
lines = [[words[0]]]
|
||||||
|
word_index = 1
|
||||||
|
line_index = 0
|
||||||
|
while word_index < len(words):
|
||||||
|
while get_width(' '.join(lines[line_index]) + ' ' + words[word_index], font) < text_box_size[0]:
|
||||||
|
lines[line_index].append(words[word_index])
|
||||||
|
word_index += 1
|
||||||
|
if word_index >= len(words) - 1:
|
||||||
|
break
|
||||||
|
line_index += 1
|
||||||
|
lines.append([])
|
||||||
|
|
||||||
|
print(goal_ratio, current_ratio, fontsize, text_box_size, get_dims(wrapped_text, font))
|
||||||
|
print(lines)
|
||||||
|
|
||||||
|
# Drawing the quote and the attribution
|
||||||
|
wrapped_text = '\n'.join([' '.join(line) for line in lines])
|
||||||
|
|
||||||
|
draw.multiline_text((margin, margin), wrapped_text, font=font, fill=(255,255,255), stroke_width=int(0.1*global_scale))
|
||||||
|
|
||||||
|
|
||||||
|
attribution = f'Verse {verse_index} from "Tao Te Ching" translated by Carol Deppe. Font "Compass" by somepx.'
|
||||||
|
fontsize = 10*global_scale
|
||||||
|
font = ImageFont.truetype(font_path, fontsize)
|
||||||
|
while get_width(attribution, font) < size[0]*0.9:
|
||||||
|
fontsize += global_scale
|
||||||
|
font = ImageFont.truetype(font_path, fontsize)
|
||||||
|
|
||||||
|
w, h = get_dims(attribution, font)
|
||||||
|
print(w, h, size)
|
||||||
|
attr_margin = int((size[0]-w)/2)
|
||||||
|
draw.multiline_text((attr_margin, size[1]-h*2.5), attribution, font=font, fill=(255,255,255), stroke_width=int(0.1*global_scale))
|
||||||
|
|
||||||
|
image = image.resize((size[0]//global_scale, size[1]//global_scale), resample=Image.NEAREST)
|
||||||
|
# image.save("image.png")
|
||||||
|
|
||||||
|
# And off to the kindle
|
||||||
|
image_bytes = io.BytesIO()
|
||||||
|
image.save(image_bytes, format='PNG')
|
||||||
|
image_bytes = image_bytes.getvalue()
|
||||||
|
|
||||||
|
requests.post('http://kindle.sn0w.cx/data', data=image_bytes)
|
BIN
kindle_photo.jpg
Normal file
BIN
kindle_photo.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.4 MiB |
BIN
kindle_photo.png
Normal file
BIN
kindle_photo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 292 KiB |
Loading…
Reference in a new issue