-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
196 lines (168 loc) · 8.28 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
from dotenv import dotenv_values
from exa_py import Exa
import os
from PIL import Image
import re
import replicate
import sendgrid
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (
Mail)
import streamlit as st
with open('./style/style.css') as f:
css = f.read()
st.markdown(f'<style>{css}</style>', unsafe_allow_html=True)
config = dotenv_values(".env")
EXA_API_KEY = config.get('EXA_API_KEY')
SENDGRID_API_KEY = config.get('SENDGRID_API_KEY')
ANTHROPIC_API_KEY = config.get('ANTHROPIC_API_KEY')
OPENAI_API_KEY = config.get("OPENAI_API_KEY")
anthropic = Anthropic(
api_key=ANTHROPIC_API_KEY
)
os.environ["REPLICATE_API_TOKEN"] = config.get("REPLICATE_API_TOKEN") # Replicate
def main():
st.title("Love Poem Generator w/ Astrology❤️ 💌")
st.write("Built w/ Anthropic, SendGrid, Streamlit, and Replicate")
image = Image.open('pikalove.png')
st.image(image)
receiver_name = st.text_input("Poem receiver name")
receiver_description = st.text_area(
"Describe the person receiving the poem",
"What do they like?"
)
model_toggle = st.radio("What LLM would you like to use", # lol it rhymes
[":rainbow[llama-2-70b-chat]", "***Claude***"],
captions = ["Hosted on Replicate", "Thank you, Anthropic"])
addons = st.multiselect(
'What would you like your poem to include?',
['humor', 'Star Wars quotes', 'Shrek reference', 'Taylor Swift lyrics', 'Klay Thompson quote'],
['Star Wars quotes', 'Shrek reference']
)
st.write('You selected:', addons)
astrology_sign = st.selectbox(
'What is their astrology sign? ♓️♈️',
['Virgo', 'Gemini', 'Leo', 'Libra', 'Sagittarius', 'Taurus', 'Aquarius', 'Aries', 'Capricorn', 'Cancer', 'Scorpio', 'Pisces']
)
st.write('You selected:', astrology_sign)
user_email = st.text_input("Email to send love poem to📧", "[email protected]")
poem = ''
if st.button('Generate a poem w/ AI 🧠🤖') and astrology_sign and addons and model_toggle and receiver_name and receiver_description and user_email:
with st.spinner('Processing📈...'):
exa = Exa(EXA_API_KEY)
exa_resp = exa.search(
f"thoughtful, fun gift for someone who's a {astrology_sign} and is described as {receiver_description}",
num_results=3,
start_crawl_date="2024-01-01",
end_crawl_date="2024-02-14",
)
print(exa_resp)
# regex pattern to extract title, URL, and score
pattern = r"Title: (.+)\nURL: (.+)\nID: .*\nScore: ([\d.]+)"
# Find all matches w/ the regex pattern
matches = re.findall(pattern, str(exa_resp))
# Iterate over the matches and add the extracted information to an array of gifts
gifts = []
for match in matches:
title, url, score = match
gifts.append(f'{title.strip()}: {url.strip()}')
COPY_PROMPT = f"""
You are a copy editor. Edit the following blurb and return only that edited blurb, ensuring the only pronouns used are "I": {receiver_description}.
There should be no preamble.
"""
if model_toggle == "***Claude***":
completion1 = anthropic.completions.create(
model="claude-instant-1.2", # claude-2.1
max_tokens_to_sample=700,
prompt=f"{HUMAN_PROMPT}: {COPY_PROMPT}. {AI_PROMPT}",
)
print(completion1.completion)
newPronouns = completion1.completion
MAIN_PROMPT= f"""
Please make me laugh by writing a short, silly, lighthearted, complimentary, lovey-dovey poem that rhymes about the following person named {receiver_name}.
<receiver_description>{newPronouns}</receiver_description>.
I would enjoy it if the poem also jokingly included the common characteristics of a person that has the astrological sign of {astrology_sign}
and something about {addons}.
Return only the poem where each new line ends with a new line character.
"""
completion = anthropic.completions.create(
model="claude-2.1",
max_tokens_to_sample=1000,
prompt=f"{HUMAN_PROMPT}: {MAIN_PROMPT}. {AI_PROMPT}",
)
newpoem = completion.completion
print(newpoem)
st.markdown(f'Generated poem: {newpoem}')
elif model_toggle == ":rainbow[llama-2-70b-chat]":
editpronouns = replicate.run(
"meta/llama-2-70b-chat:02e509c789964a7ea8736978a43525956ef40397be9033abf9fd2badfe68c9e3",
input={
"prompt": COPY_PROMPT,
"max_new_tokens": 700
}
)
newpronounsblurb = ''
for item in editpronouns:
newpronounsblurb+=item
print(item, end="")
print("newpronounsblurb ", newpronounsblurb)
MAIN_PROMPT= f"""
With no preamble, please make me laugh by writing a short, silly, lighthearted, complimentary, lovey-dovey poem that rhymes about the following person named {receiver_name}.
<receiver_description>{newpronounsblurb}</receiver_description>.
I would enjoy it if the poem also jokingly included the common characteristics of a person that has the astrological sign of {astrology_sign}
and something about {addons}.
Return only the poem.
"""
poem = replicate.run(
"meta/llama-2-70b-chat:02e509c789964a7ea8736978a43525956ef40397be9033abf9fd2badfe68c9e3",
input={
"prompt": MAIN_PROMPT,
"max_new_tokens": 1000
}
)
newpoem = ''
for item in poem:
newpoem+=item
print(item, end="")
print("newpoem ", newpoem)
st.markdown(f'The generated poem: {newpoem}')
output_pic = replicate.run(
"stability-ai/stable-diffusion:ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e4",
input={
"prompt": f"Please generate a G-rated cute image of a {astrology_sign} including hearts that I can show my manager",
"width": 448,
"height": 448,
"negative_prompt": "nsfw",
}
)
print(output_pic[0])
message = Mail(
from_email='[email protected]',
to_emails=user_email,
subject='Personal poem for you!❤️',
html_content=f'''
<img src="{output_pic[0]}"</img>
<p>{newpoem}</p>
<p> ❤️😘🥰</p>
'''
)
sg = SendGridAPIClient(api_key=SENDGRID_API_KEY)
response = sg.send(message)
print(response.status_code, response.body, response.headers)
if response.status_code == 202:
st.success("Email sent! Tell your ✨friend✨ to check their email for their poem and image")
print(f"Response Code: {response.status_code} \n Email sent!")
else:
st.warning("Email not sent--check console")
else:
st.write("Check that you filled out each textbox and selected something for each question!")
footer="""
<footer>
<p>Developed with ❤ in SF🌁</p>
<p>✅ out the code on <a href="https://github.com/elizabethsiegle/loveletter-generator-anthropic-sendgrid" target="_blank">GitHub</a></p>
</footer>
"""
st.markdown(footer,unsafe_allow_html=True)
if __name__ == "__main__":
main()