reysarms commited on
Commit
21dcf87
Β·
1 Parent(s): 624fa4f

final changes to poetry app

Browse files
Files changed (1) hide show
  1. app.py +21 -17
app.py CHANGED
@@ -5,14 +5,14 @@ from dotenv import load_dotenv
5
 
6
  # Load environment variables
7
  load_dotenv()
8
- api_key = os.getenv("GEMINI_API_KEY") # Use Google Gemini API key
9
 
10
  # Check if API key is set
11
  if not api_key:
12
  st.error("❌ Error: Google API key is missing. Please check your .env file.")
13
  st.stop()
14
 
15
- # Initialize Google Gemini AI client
16
  genai.configure(api_key=api_key)
17
 
18
  # Streamlit UI
@@ -20,41 +20,45 @@ st.set_page_config(page_title="REYREY's AI Poetry Translator", page_icon="🎭",
20
  st.title("πŸ“ REYREY's Poetry Translator 🎭")
21
  st.write("Enter a phrase, sentence, or paragraph, and I'll transform it into poetry!")
22
 
23
- # User input
24
  text_input = st.text_area("Enter text:", placeholder="Type something here...")
25
 
26
- # Poetry style selection
27
  poetry_style = st.selectbox(
28
  "Choose a poetry style:",
29
  ["Shakespearean", "Haiku", "Free Verse", "Sonnet", "Limerick", "Rhyming Couplets"]
30
  )
31
 
32
- # Function to call Google Gemini API
33
- def generate_poetry(text, style):
34
  try:
35
  prompt = f"Convert the following text into {style} poetry:\n\n{text}\n\nPoem:"
36
-
37
- model = genai.GenerativeModel("gemini-pro") # Use Google's Gemini Pro model
38
  response = model.generate_content(prompt)
39
 
40
- # βœ… Check if response has valid candidates
41
- if response.candidates:
42
- for candidate in response.candidates:
43
- if candidate.finish_reason == "STOP":
44
- return candidate.content.parts[0].text.strip()
45
 
46
- # βœ… Handle safety filter blocking content
47
- return "❌ AI Response was blocked due to content safety filters."
 
 
 
 
 
 
 
48
 
49
  except Exception as e:
50
  return f"❌ Error generating poem: {str(e)}"
51
 
52
- # Generate poetry on button click
53
  if st.button("Generate Poetry ✨"):
54
  if text_input:
55
  with st.spinner("Creating your poem... 🎭"):
56
  poem = generate_poetry(text_input, poetry_style)
57
- if poem.startswith("❌ Error") or poem.startswith("❌ AI Response"):
58
  st.error(poem)
59
  else:
60
  st.success("Here’s your poetic masterpiece:")
 
5
 
6
  # Load environment variables
7
  load_dotenv()
8
+ api_key = os.getenv("GEMINI_API_KEY") # Gets the Google Gemini API key
9
 
10
  # Check if API key is set
11
  if not api_key:
12
  st.error("❌ Error: Google API key is missing. Please check your .env file.")
13
  st.stop()
14
 
15
+ # Set up Google Gemini AI
16
  genai.configure(api_key=api_key)
17
 
18
  # Streamlit UI
 
20
  st.title("πŸ“ REYREY's Poetry Translator 🎭")
21
  st.write("Enter a phrase, sentence, or paragraph, and I'll transform it into poetry!")
22
 
23
+ # Get user input
24
  text_input = st.text_area("Enter text:", placeholder="Type something here...")
25
 
26
+ # Let user choose a poetry style
27
  poetry_style = st.selectbox(
28
  "Choose a poetry style:",
29
  ["Shakespearean", "Haiku", "Free Verse", "Sonnet", "Limerick", "Rhyming Couplets"]
30
  )
31
 
32
+ # Generates a poem using Google Gemini AI
33
+ def generate_poetry(text, style, retry=False):
34
  try:
35
  prompt = f"Convert the following text into {style} poetry:\n\n{text}\n\nPoem:"
36
+ model = genai.GenerativeModel("gemini-pro") # Uses Google's Gemini Pro model
 
37
  response = model.generate_content(prompt)
38
 
39
+ # Checks if AI returned a valid response
40
+ if response and hasattr(response, "text") and response.text:
41
+ return response.text.strip()
 
 
42
 
43
+ # Retries with a softer prompt if the first attempt is blocked
44
+ if not retry:
45
+ softer_prompt = f"Write a short {style} poem based on this idea: {text}"
46
+ response = model.generate_content(softer_prompt)
47
+ if response and hasattr(response, "text") and response.text:
48
+ return response.text.strip()
49
+
50
+ # Returns a friendly message if AI refuses to generate a poem
51
+ return "⚠️ AI couldn't generate a poem. Try rewording your input."
52
 
53
  except Exception as e:
54
  return f"❌ Error generating poem: {str(e)}"
55
 
56
+ # Runs when the user clicks the button
57
  if st.button("Generate Poetry ✨"):
58
  if text_input:
59
  with st.spinner("Creating your poem... 🎭"):
60
  poem = generate_poetry(text_input, poetry_style)
61
+ if poem.startswith("❌ Error"):
62
  st.error(poem)
63
  else:
64
  st.success("Here’s your poetic masterpiece:")