awacke1 commited on
Commit
099e596
·
1 Parent(s): b9307d0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image, ImageDraw, ImageFont
3
+ import io
4
+ import base64
5
+ from datetime import datetime
6
+
7
+ def calculate_font_size(img_width, img_height, text):
8
+ max_font_size = int(img_width * 0.1)
9
+ min_font_size = int(img_width * 0.02)
10
+
11
+ if len(text) < 5:
12
+ return max_font_size
13
+ elif len(text) < 20:
14
+ return int((max_font_size + min_font_size) / 2)
15
+ else:
16
+ return min_font_size
17
+
18
+ def generate_meme(img_path, top_text, middle_text, bottom_text):
19
+ img = Image.open(img_path)
20
+ draw = ImageDraw.Draw(img)
21
+
22
+ font_path = "/path/to/your/font.ttf"
23
+ font_size_top = calculate_font_size(img.width, img.height, top_text)
24
+ font_size_middle = calculate_font_size(img.width, img.height, middle_text)
25
+ font_size_bottom = calculate_font_size(img.width, img.height, bottom_text)
26
+
27
+ font_top = ImageFont.truetype(font_path, font_size_top)
28
+ font_middle = ImageFont.truetype(font_path, font_size_middle)
29
+ font_bottom = ImageFont.truetype(font_path, font_size_bottom)
30
+
31
+ draw.text((10,10), top_text, font=font_top, fill="white")
32
+ draw.text((10,img.height // 2 - font_size_middle // 2), middle_text, font=font_middle, fill="white")
33
+ draw.text((10,img.height - 10 - font_size_bottom), bottom_text, font=font_bottom, fill="white")
34
+
35
+ return img
36
+
37
+ def get_image_download_link(img, filename="meme.png"):
38
+ buffered = io.BytesIO()
39
+ img.save(buffered, format="PNG")
40
+ img_str = base64.b64encode(buffered.getvalue()).decode()
41
+ href = f'<a href="data:image/png;base64,{img_str}" download="{filename}">Download Image</a>'
42
+ return href
43
+
44
+ st.title("Meme Generator")
45
+
46
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png"])
47
+
48
+ if uploaded_file is not None:
49
+ st.image(uploaded_file, caption='Uploaded Image.', use_column_width=True)
50
+
51
+ top_text = st.text_input("Enter top text")
52
+ middle_text = st.text_input("Enter middle text")
53
+ bottom_text = st.text_input("Enter bottom text")
54
+
55
+ if st.button("Generate Meme"):
56
+ result_img = generate_meme(uploaded_file, top_text, middle_text, bottom_text)
57
+
58
+ filename = datetime.now().strftime('%Y%m%d%H%M%S') + ".png"
59
+ st.image(result_img, caption='Generated Meme', use_column_width=True)
60
+
61
+ st.markdown(get_image_download_link(result_img, filename), unsafe_allow_html=True)
62
+
63
+ # References
64
+ st.write("### References:")
65
+ st.write(f"- [DOI](https://doi.org/10.57967/hf/0428)")
66
+ st.write(f"- [arXiv](https://arxiv.org/abs/1910.09700)")