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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# prompt: create a function with documentation for connect to GPT4o and ask for the weather
|
2 |
+
# Note: the above uses the old API, so I look up the current API update the code.
|
3 |
+
# Manual: Update to horoscopes templates
|
4 |
+
# prompt: print out the zodiac signs
|
5 |
+
|
6 |
+
import datetime
|
7 |
+
import openai
|
8 |
+
import os
|
9 |
+
from openai import OpenAI
|
10 |
+
client = OpenAI()
|
11 |
+
#
|
12 |
+
# Set your OpenAI API key
|
13 |
+
#
|
14 |
+
openai.api_key = os.getenv("OPENAI_API_KEY") # OpenAI API key: https://platform.openai.com/api-keys
|
15 |
+
#
|
16 |
+
# For convience to access to the Zodiac signs
|
17 |
+
#
|
18 |
+
zodiac_signs = [
|
19 |
+
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
|
20 |
+
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"
|
21 |
+
]
|
22 |
+
#
|
23 |
+
now = datetime.datetime.now()
|
24 |
+
today = f"{now.strftime('%A')}, {now.strftime('%B')} {now.strftime('%d')}, {now.strftime('%Y')}"
|
25 |
+
#
|
26 |
+
# Define the horoscope function
|
27 |
+
#
|
28 |
+
def fetch_horoscope(zodiac_sign=zodiac_signs[3],
|
29 |
+
name="Hanna",
|
30 |
+
person="teen girl",
|
31 |
+
focus="in school",
|
32 |
+
nationality="American",
|
33 |
+
model="gpt-4o"):
|
34 |
+
"""Connects to GPT-4 and asks for the Horoscope.
|
35 |
+
|
36 |
+
Args:
|
37 |
+
zodiac_sign: (string) one of the 12 zodiac signs.
|
38 |
+
name: (string) the name of the person.
|
39 |
+
person: (string) the person's description.
|
40 |
+
focus: (string) the person's focus.
|
41 |
+
model: (string) the model to use.
|
42 |
+
Raises:
|
43 |
+
Exception: If the OpenAI API call fails.
|
44 |
+
Returns:
|
45 |
+
A string containing the horoscope and if errors return an error message.
|
46 |
+
"""
|
47 |
+
#
|
48 |
+
# model choice, "gpt-4o", "gpt-4o-mini"
|
49 |
+
# more choice at: https://platform.openai.com/docs/models/gpt-4o-mini
|
50 |
+
# model = "gpt-4o"
|
51 |
+
#
|
52 |
+
# create prompt templates (Prompt Engineering)
|
53 |
+
#
|
54 |
+
msg1 = {"role": "system", "content": "You are a helpful assistant."}
|
55 |
+
#
|
56 |
+
_input = f"Generate a daily horoscope for {zodiac_sign} for {today} with a focus on career and relationships. Include {zodiac_sign}'s traits, and mention any relevant celestial events or planetary alignments. Provide practical advice that aligns with the day’s energy. Incorporate lucky elements such as a color, number, or time of day to enhance personalization. Ensure the tone is witty, positive, uplifting, and inspiring."
|
57 |
+
#
|
58 |
+
_output = f"The output is a story with age appropiate tone to {name}, a {person}, {focus}, and nationality is {nationality}. No bullet points, no heading."
|
59 |
+
#
|
60 |
+
msg2 = {"role": "user", "content": f"{_input} {_output}"}
|
61 |
+
#
|
62 |
+
prompt_template = [msg1, msg2]
|
63 |
+
#
|
64 |
+
# Ask GPT4
|
65 |
+
#
|
66 |
+
try:
|
67 |
+
completion = client.chat.completions.create(
|
68 |
+
model=model,
|
69 |
+
messages=prompt_template
|
70 |
+
)
|
71 |
+
# print(completion.choices[0].message)
|
72 |
+
horoscope_info = completion.choices[0].message
|
73 |
+
return horoscope_info.content
|
74 |
+
#
|
75 |
+
except Exception as e:
|
76 |
+
return f"An error occurred: {e}"
|
77 |
+
#
|
78 |
+
# Example usage:
|
79 |
+
# horoscope_reading = fetch_horoscope(zodiac_signs[0])
|
80 |
+
# print(f"Your horoscopes for today is:\n\n {horoscope_reading.content}")
|
81 |
+
|
82 |
+
|
83 |
+
# prompt: write a function with documentation to use GPT4 to generate an image
|
84 |
+
# Note: add in prompt template (prompt engineer)
|
85 |
+
|
86 |
+
import os
|
87 |
+
import openai
|
88 |
+
from openai import OpenAI
|
89 |
+
|
90 |
+
def fetch_image(prompt, n=1, size="1024x1024", model_image="dall-e-3"):
|
91 |
+
"""Generates an image using OpenAI's DALL-E 2 API based on a given text prompt.
|
92 |
+
|
93 |
+
Args:
|
94 |
+
prompt: (string) A text description of the desired image.
|
95 |
+
n: (int) The number of images to generate (default is 1).
|
96 |
+
size: (string) The size of the generated images (default is 1024x1024).
|
97 |
+
Other options include "256x256" and "512x512" and more.
|
98 |
+
model: (string) The model to use for image generation (default is "dall-e-3") or dall-e-2.
|
99 |
+
Raises:
|
100 |
+
Exception: If the OpenAI API call fails.
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
A list of image URLs, or an error message if the API call fails.
|
104 |
+
"""
|
105 |
+
#
|
106 |
+
# Define the prompt template
|
107 |
+
#
|
108 |
+
prompt_template = f"Draw a realism beautiful watercolor image in pastel tone with no text, no writing, and no wording for the person in the following horoscope: {prompt}"
|
109 |
+
#
|
110 |
+
# Request to generate image
|
111 |
+
#
|
112 |
+
try:
|
113 |
+
client = OpenAI()
|
114 |
+
response = client.images.generate(
|
115 |
+
model=model_image,
|
116 |
+
prompt=prompt_template,
|
117 |
+
n=n,
|
118 |
+
size=size
|
119 |
+
)
|
120 |
+
image_urls = [image.url for image in response.data]
|
121 |
+
return image_urls
|
122 |
+
except Exception as e:
|
123 |
+
return f"An unexpected error occurred: {e}"
|
124 |
+
|
125 |
+
|
126 |
+
# prompt: write a python function to take the output of OpenAI client.images.generate() function url and using PIL to create an image from it.
|
127 |
+
# prompt: have error: Error downloading image: No connection adapters were found for "['https://oaidalleapiprodscus.blob.core.windows.net/private/org-A0exPbLvAU5v7R8klVyjjESv/user-N17uY5bUcWfRy95Xxs6huBmQ/img-QF2y2rPhSjGoJO25XeUdLqLD.png?st=2024-11-08T05%3A59%3A14Z&se=2024-11-08T07%3A59%3A14Z&sp=r&sv=2024-08-04&sr=b&rscd=inline&rsct=image/png&skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-11-07T10%3A09%3A58Z&ske=2024-11-08T10%3A09%3A58Z&sks=b&skv=2024-08-04&sig=bJziZ5sNTiIyl77YfNoFMfc/KB/NL9zHBHSsv2SnlGY%3D']"
|
128 |
+
|
129 |
+
import requests
|
130 |
+
from PIL import Image
|
131 |
+
from io import BytesIO
|
132 |
+
|
133 |
+
def generate_image_from_url(image_url):
|
134 |
+
"""
|
135 |
+
Downloads an image from a URL and creates a PIL Image object.
|
136 |
+
|
137 |
+
Args:
|
138 |
+
image_url (str): The URL of the image.
|
139 |
+
|
140 |
+
Returns:
|
141 |
+
PIL.Image.Image: A PIL Image object created from the downloaded image.
|
142 |
+
"""
|
143 |
+
try:
|
144 |
+
# Ensure the URL is a string and strip any extraneous characters
|
145 |
+
if isinstance(image_url, list) and len(image_url) == 1:
|
146 |
+
image_url = image_url[0] # Extract URL if it's in a list
|
147 |
+
if not isinstance(image_url, str):
|
148 |
+
raise ValueError("The image_url must be a string.")
|
149 |
+
|
150 |
+
# Fetch the image data from the URL
|
151 |
+
response = requests.get(image_url)
|
152 |
+
response.raise_for_status() # Ensure the request was successful
|
153 |
+
|
154 |
+
# Load the image into a PIL Image object
|
155 |
+
image = Image.open(BytesIO(response.content))
|
156 |
+
return image
|
157 |
+
|
158 |
+
except requests.exceptions.RequestException as e:
|
159 |
+
print(f"Error fetching the image from URL: {e}")
|
160 |
+
return None
|
161 |
+
except Exception as e:
|
162 |
+
print(f"Error processing the image: {e}")
|
163 |
+
return None
|
164 |
+
|
165 |
+
# prompt: write tell_me function with inline documentation using *args, **kwargs calling fetch_horoscope and use the output to call fetch_image function return both horoscope text and image link
|
166 |
+
# Note: minor manual debug
|
167 |
+
from logging import error
|
168 |
+
#
|
169 |
+
def tell_me(*args, **kwargs):
|
170 |
+
"""Fetches a horoscope and generates an image based on it.
|
171 |
+
|
172 |
+
This function combines the functionality of fetch_horoscope and fetch_image.
|
173 |
+
It takes the same arguments as fetch_horoscope, fetches the horoscope,
|
174 |
+
and then uses the horoscope text as a prompt for fetch_image to generate an image.
|
175 |
+
|
176 |
+
Args:
|
177 |
+
*args: Variable length argument list. Passed to fetch_horoscope.
|
178 |
+
**kwargs: Arbitrary keyword arguments. Passed to fetch_horoscope.
|
179 |
+
|
180 |
+
Returns:
|
181 |
+
A dictionary containing the horoscope_text and image_url.
|
182 |
+
Returns an error message if either API call fails.
|
183 |
+
"""
|
184 |
+
try:
|
185 |
+
horoscope_text = fetch_horoscope(
|
186 |
+
zodiac_sign=kwargs.get('zodiac_sign', 'Aquarius'),
|
187 |
+
name=kwargs.get('name', "Hanna"),
|
188 |
+
person=kwargs.get('person', "teen girl"),
|
189 |
+
focus=kwargs.get('focus', "in school"),
|
190 |
+
model=kwargs.get('model', "gpt-4o"))
|
191 |
+
|
192 |
+
image_url = fetch_image(
|
193 |
+
prompt=kwargs.get('prompt', horoscope_text),
|
194 |
+
n=kwargs.get('n', 1),
|
195 |
+
size=kwargs.get('size', "1024x1024"),
|
196 |
+
model_image=kwargs.get('model_image', "dall-e-3")
|
197 |
+
)
|
198 |
+
return {"horoscope_text":horoscope_text, "image_url":image_url}
|
199 |
+
except Exception as e:
|
200 |
+
error_message = f"An unexpected error occurred in tell_me(): {e}"
|
201 |
+
return {"horoscope_text":error_message, "image_url":"no_url"}
|
202 |
+
|
203 |
+
# # Example usage
|
204 |
+
# json_output = tell_me(zodiac_sign="Taurus")
|
205 |
+
# print(f"Horoscopes:\n{json_output.horoscope_text}:\n\nImage URL:\n{json_output.image_url}")
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
# prompt: create a gradio code for input 5 item, person_name, horoscope_sign, job, focus, and nationality, and output has text and image
|
210 |
+
|
211 |
+
import gradio
|
212 |
+
|
213 |
+
# ... (rest of your existing code) ...
|
214 |
+
|
215 |
+
def gradio_tell_me(person_name, horoscope_sign, job, focus, nationality):
|
216 |
+
|
217 |
+
# HARD-CODE to test
|
218 |
+
# horoscope_text = dragon_flying
|
219 |
+
# image_url = dragon_img_url
|
220 |
+
data=tell_me(zodiac_sign=horoscope_sign,
|
221 |
+
name=person_name,person=job,focus=focus,nationality=nationality)
|
222 |
+
horoscope_text=data['horoscope_text']
|
223 |
+
image_url=data['image_url']
|
224 |
+
try:
|
225 |
+
image = generate_image_from_url(image_url)
|
226 |
+
except Exception as e:
|
227 |
+
print(f"Error generating image: {e}")
|
228 |
+
image = None # Return None if error happens
|
229 |
+
|
230 |
+
return horoscope_text, image
|
231 |
+
|
232 |
+
iface = gradio.Interface(
|
233 |
+
fn=gradio_tell_me,
|
234 |
+
inputs=[
|
235 |
+
gradio.Textbox(label="Person Name"),
|
236 |
+
gradio.Dropdown(choices=zodiac_signs, label="Horoscope Sign"),
|
237 |
+
gradio.Textbox(label="Job"),
|
238 |
+
gradio.Textbox(label="Focus"),
|
239 |
+
gradio.Textbox(label="Nationality"),
|
240 |
+
],
|
241 |
+
outputs=[
|
242 |
+
gradio.Textbox(label="Horoscope"),
|
243 |
+
gradio.Image(label="Horoscope Image")
|
244 |
+
],
|
245 |
+
title="Horoscope Generator",
|
246 |
+
description="Generate a personalized horoscope and image."
|
247 |
+
)
|
248 |
+
|
249 |
+
iface.launch()
|
250 |
+
|
251 |
+
|
252 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
openai
|
2 |
+
gradio
|