1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- def get_verse_image(verse):
- """создает картинку, сохраняет в файл и возвращает имя файла"""
- verse_lines = verse['text'].split('\n')
- shift = 0
- one_stoke = False
- space_mult = 1
- if len(verse_lines) == 4:
- shift = 90
- elif len(verse_lines) == 1:
- one_stoke = True
- words = verse_lines[0].split(" ")
- lines = len(words) // 5
- if len(words) % 5 != 0:
- lines += 1
- verse_lines = []
- for l in range(lines):
- if l == lines - 1:
- verse_lines.append(" ".join(words[l*5:]))
- else:
- verse_lines.append(" ".join(words[l*5:l*5+5]))
- print(verse_lines)
- elif len(verse_lines) == 3:
- shift = 100
- elif len(verse_lines) == 6:
- shift = -10
- space_mult = 0.8
- if len(verse['text']) > 160:
- shift = 10
- space_mult = 0.9
- y_pos = 120
- lines = ""
- for line in verse_lines:
- splited_line = split_line(line)
- l = f'<tspan x="50%" y="{y_pos + shift}">{splited_line[0]}</tspan>'
- l1 = ""
- if len(splited_line) == 2:
- anchor = "middle" if one_stoke else "end"
- x_cord = 'x="1500"' if not one_stoke else 'x="50%"'
- l1 = f'<tspan {x_cord} y="{y_pos + 90 + shift}" \
- text-anchor="{anchor}">{splited_line[1]}</tspan>'
- y_pos += 40
- lines += f"{l}\n{l1}\n"
- y_pos += int(150 * space_mult)
- template = f"""
- <svg
- width="1600"
- height="900"
- viewBox="0 0 1600 900"
- version="1.1"
- >
- <rect width="100%" height="100%" fill="white" />
- <text
- style="font-style:italic;font-weight:normal;font-size:75px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#00004f;fill-opacity:1"
- dominant-baseline="middle"
- text-anchor="middle">
- {lines}
- <tspan text-anchor="end" style="font-weight:bold;font-size:50px" x="1570" y="880">{verse['title']}</tspan>
- </text>
- </svg>
- """
- file_name = f"img/{verse['alias'].replace(' ', '_')}.svg"
- with open(file_name, "w") as file:
- file.write(template)
-
- return file_name
- def split_line(text):
- """попытка сделать алгоритм, который делит длинные строки"""
- max_line_length = 38
- if len(text) > max_line_length:
- lines = [" ".join(text.split(" ")[:-1]), text.split(" ")[-1]]
- if len(lines[0]) > max_line_length:
- lines = [" ".join(text.split(" ")[:-2]), " ".join(text.split(" ")[-2:])]
- if len(lines[0]) > max_line_length:
- lines = [" ".join(text.split(" ")[:-3]), " ".join(text.split(" ")[-3:])]
- if len(lines[0]) > max_line_length:
- lines = ["-".join(text.split("-")[:-1]) + "-", text.split("-")[-1]]
- if len(lines[0]) > max_line_length:
- lines = ["-".join(text.split("-")[:-2]) + "-", "-".join(text.split("-")[-2:])]
- if len(lines[0]) > max_line_length:
- lines = ["-".join(text.split("-")[:-3]) + "-", "-".join(text.split("-")[-3:])]
- if len(lines[0]) > max_line_length:
- lines = ["-".join(text.split("-")[:-4]) + "-", "-".join(text.split("-")[-4:])]
- return lines
- return [text]
|