update
Browse files- quote_generator_gemini.py +86 -35
quote_generator_gemini.py
CHANGED
|
@@ -27,30 +27,42 @@ class QuoteGenerator:
|
|
| 27 |
raise ValueError("GEMINI_API_KEY not found in environment variables")
|
| 28 |
|
| 29 |
genai.configure(api_key=api_key)
|
| 30 |
-
self.model = genai.GenerativeModel('gemini-
|
| 31 |
|
| 32 |
-
# Persistent storage for quote history
|
| 33 |
self.history_file = history_file
|
| 34 |
-
self.
|
| 35 |
-
self.max_history = 100 # Keep last 100 quotes
|
| 36 |
|
| 37 |
-
def _load_history(self) ->
|
| 38 |
-
"""Load quote history from persistent storage"""
|
| 39 |
try:
|
| 40 |
if os.path.exists(self.history_file):
|
| 41 |
with open(self.history_file, 'r') as f:
|
| 42 |
data = json.load(f)
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Could not load history: {e}")
|
| 46 |
-
return
|
| 47 |
|
| 48 |
def _save_history(self):
|
| 49 |
"""Save quote history to persistent storage"""
|
| 50 |
try:
|
| 51 |
os.makedirs(os.path.dirname(self.history_file), exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
with open(self.history_file, 'w') as f:
|
| 53 |
-
json.dump({'
|
| 54 |
except Exception as e:
|
| 55 |
print(f"Could not save history: {e}")
|
| 56 |
|
|
@@ -66,34 +78,47 @@ class QuoteGenerator:
|
|
| 66 |
A unique quote string
|
| 67 |
"""
|
| 68 |
|
| 69 |
-
# Get
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
recent_quotes_text = ""
|
| 71 |
-
if
|
| 72 |
-
recent_quotes_text = "\n\
|
| 73 |
-
for i, quote in enumerate(
|
| 74 |
recent_quotes_text += f"{i}. {quote}\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
# Build prompt with variety instructions
|
| 77 |
-
prompt = f"""Generate a UNIQUE and powerful {niche} quote suitable for an Instagram/TikTok video.
|
| 78 |
|
| 79 |
Visual Style: {style}
|
| 80 |
|
| 81 |
-
CRITICAL REQUIREMENTS:
|
| 82 |
- 2-4 sentences maximum (can be longer if deeply meaningful)
|
| 83 |
-
- Must be
|
| 84 |
- Inspirational and impactful
|
| 85 |
-
- Deep and meaningful insights
|
| 86 |
- Fresh perspective that viewers haven't heard before
|
| 87 |
- Unexpected wisdom or unique angle
|
| 88 |
- DO NOT use clichés or overused phrases
|
|
|
|
| 89 |
|
| 90 |
{recent_quotes_text}
|
| 91 |
|
| 92 |
-
IMPORTANT: Your quote must be COMPLETELY ORIGINAL
|
| 93 |
-
- Core message and theme
|
| 94 |
-
- Wording and phrasing
|
| 95 |
-
- Perspective and angle
|
| 96 |
-
- Examples or metaphors used
|
|
|
|
|
|
|
| 97 |
|
| 98 |
Return ONLY the quote text, nothing else. No quotation marks, no attribution."""
|
| 99 |
|
|
@@ -115,26 +140,53 @@ Return ONLY the quote text, nothing else. No quotation marks, no attribution."""
|
|
| 115 |
quote = response.text.strip()
|
| 116 |
quote = quote.strip('"').strip("'").strip()
|
| 117 |
|
| 118 |
-
#
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
self._save_history()
|
| 121 |
|
|
|
|
|
|
|
|
|
|
| 122 |
return quote
|
| 123 |
|
| 124 |
except Exception as e:
|
| 125 |
raise Exception(f"Gemini quote generation failed: {str(e)}")
|
| 126 |
|
| 127 |
def get_stats(self) -> dict:
|
| 128 |
-
"""Get statistics about quote generation"""
|
|
|
|
| 129 |
return {
|
| 130 |
-
"total_quotes_generated":
|
| 131 |
-
"
|
| 132 |
-
"
|
| 133 |
}
|
| 134 |
|
| 135 |
-
def clear_history(self):
|
| 136 |
-
"""Clear quote history (use with caution)
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
self._save_history()
|
| 139 |
|
| 140 |
|
|
@@ -278,10 +330,9 @@ if __name__ == "__main__":
|
|
| 278 |
stats = generator.get_stats()
|
| 279 |
print("\nStats:")
|
| 280 |
print(f" Total generated: {stats['total_quotes_generated']}")
|
| 281 |
-
print(f"
|
| 282 |
-
print(f"
|
| 283 |
|
| 284 |
except Exception as e:
|
| 285 |
print(f"Error: {e}")
|
| 286 |
print("\nMake sure GEMINI_API_KEY is set in environment variables")
|
| 287 |
-
|
|
|
|
| 27 |
raise ValueError("GEMINI_API_KEY not found in environment variables")
|
| 28 |
|
| 29 |
genai.configure(api_key=api_key)
|
| 30 |
+
self.model = genai.GenerativeModel('gemini-1.5-flash') # Updated model name
|
| 31 |
|
| 32 |
+
# Persistent storage for quote history - PER NICHE
|
| 33 |
self.history_file = history_file
|
| 34 |
+
self.quotes_by_niche = self._load_history() # Returns dict
|
| 35 |
+
self.max_history = 100 # Keep last 100 quotes PER NICHE
|
| 36 |
|
| 37 |
+
def _load_history(self) -> dict:
|
| 38 |
+
"""Load quote history from persistent storage - organized by niche"""
|
| 39 |
try:
|
| 40 |
if os.path.exists(self.history_file):
|
| 41 |
with open(self.history_file, 'r') as f:
|
| 42 |
data = json.load(f)
|
| 43 |
+
# Support both old format (list) and new format (dict)
|
| 44 |
+
if 'quotes_by_niche' in data:
|
| 45 |
+
print(f"📖 Loaded history for {len(data['quotes_by_niche'])} niches")
|
| 46 |
+
return data['quotes_by_niche']
|
| 47 |
+
elif 'quotes' in data:
|
| 48 |
+
# Old format - migrate
|
| 49 |
+
print("📖 Migrating to per-niche tracking")
|
| 50 |
+
return {"General": data['quotes']}
|
| 51 |
except Exception as e:
|
| 52 |
print(f"Could not load history: {e}")
|
| 53 |
+
return {}
|
| 54 |
|
| 55 |
def _save_history(self):
|
| 56 |
"""Save quote history to persistent storage"""
|
| 57 |
try:
|
| 58 |
os.makedirs(os.path.dirname(self.history_file), exist_ok=True)
|
| 59 |
+
# Save all niches, keeping last max_history per niche
|
| 60 |
+
trimmed_data = {}
|
| 61 |
+
for niche, quotes in self.quotes_by_niche.items():
|
| 62 |
+
trimmed_data[niche] = quotes[-self.max_history:]
|
| 63 |
+
|
| 64 |
with open(self.history_file, 'w') as f:
|
| 65 |
+
json.dump({'quotes_by_niche': trimmed_data}, f, indent=2)
|
| 66 |
except Exception as e:
|
| 67 |
print(f"Could not save history: {e}")
|
| 68 |
|
|
|
|
| 78 |
A unique quote string
|
| 79 |
"""
|
| 80 |
|
| 81 |
+
# Get this niche's history
|
| 82 |
+
if niche not in self.quotes_by_niche:
|
| 83 |
+
self.quotes_by_niche[niche] = []
|
| 84 |
+
|
| 85 |
+
recent_quotes = self.quotes_by_niche[niche]
|
| 86 |
+
|
| 87 |
+
# Get recent quotes to avoid (last 30 for better variety)
|
| 88 |
recent_quotes_text = ""
|
| 89 |
+
if recent_quotes:
|
| 90 |
+
recent_quotes_text = f"\n\n❌ PREVIOUSLY GENERATED {niche.upper()} QUOTES (YOU MUST AVOID THESE - DO NOT REPEAT OR PARAPHRASE):\n"
|
| 91 |
+
for i, quote in enumerate(recent_quotes[-30:], 1): # Last 30
|
| 92 |
recent_quotes_text += f"{i}. {quote}\n"
|
| 93 |
+
|
| 94 |
+
print(f"📊 {niche} history: {len(recent_quotes)} total quotes, showing last 30 to avoid")
|
| 95 |
+
else:
|
| 96 |
+
print(f"📊 No {niche} history yet - generating first quote for this niche")
|
| 97 |
|
| 98 |
+
# Build prompt with VERY strong variety instructions
|
| 99 |
+
prompt = f"""Generate a COMPLETELY UNIQUE and powerful {niche} quote suitable for an Instagram/TikTok video.
|
| 100 |
|
| 101 |
Visual Style: {style}
|
| 102 |
|
| 103 |
+
CRITICAL REQUIREMENTS - READ CAREFULLY:
|
| 104 |
- 2-4 sentences maximum (can be longer if deeply meaningful)
|
| 105 |
+
- Must be RADICALLY DIFFERENT from all previously generated quotes below
|
| 106 |
- Inspirational and impactful
|
| 107 |
+
- Deep and meaningful insights
|
| 108 |
- Fresh perspective that viewers haven't heard before
|
| 109 |
- Unexpected wisdom or unique angle
|
| 110 |
- DO NOT use clichés or overused phrases
|
| 111 |
+
- AVOID common motivational phrases like "success is", "believe in yourself", "the only limit"
|
| 112 |
|
| 113 |
{recent_quotes_text}
|
| 114 |
|
| 115 |
+
IMPORTANT: Your quote must be COMPLETELY ORIGINAL in:
|
| 116 |
+
- Core message and theme (different life area or concept)
|
| 117 |
+
- Wording and phrasing (no similar sentences)
|
| 118 |
+
- Perspective and angle (unique viewpoint)
|
| 119 |
+
- Examples or metaphors used (creative analogies)
|
| 120 |
+
|
| 121 |
+
Generate something viewers have NEVER seen before.
|
| 122 |
|
| 123 |
Return ONLY the quote text, nothing else. No quotation marks, no attribution."""
|
| 124 |
|
|
|
|
| 140 |
quote = response.text.strip()
|
| 141 |
quote = quote.strip('"').strip("'").strip()
|
| 142 |
|
| 143 |
+
# Check if this quote already exists in THIS niche
|
| 144 |
+
if quote in recent_quotes:
|
| 145 |
+
print(f"⚠️ WARNING: Generated duplicate {niche} quote! Trying again with higher temperature...")
|
| 146 |
+
# Try one more time with even higher temperature
|
| 147 |
+
response = self.model.generate_content(
|
| 148 |
+
prompt,
|
| 149 |
+
generation_config={
|
| 150 |
+
"temperature": 1.2, # Even higher
|
| 151 |
+
"top_p": 0.98,
|
| 152 |
+
"top_k": 80,
|
| 153 |
+
"max_output_tokens": 200,
|
| 154 |
+
}
|
| 155 |
+
)
|
| 156 |
+
quote = response.text.strip().strip('"').strip("'").strip()
|
| 157 |
+
|
| 158 |
+
# Add to this niche's history and save
|
| 159 |
+
self.quotes_by_niche[niche].append(quote)
|
| 160 |
self._save_history()
|
| 161 |
|
| 162 |
+
print(f"✅ Generated unique {niche} quote #{len(self.quotes_by_niche[niche])}")
|
| 163 |
+
print(f"💾 Saved to: {self.history_file}")
|
| 164 |
+
|
| 165 |
return quote
|
| 166 |
|
| 167 |
except Exception as e:
|
| 168 |
raise Exception(f"Gemini quote generation failed: {str(e)}")
|
| 169 |
|
| 170 |
def get_stats(self) -> dict:
|
| 171 |
+
"""Get statistics about quote generation - per niche"""
|
| 172 |
+
total_quotes = sum(len(quotes) for quotes in self.quotes_by_niche.values())
|
| 173 |
return {
|
| 174 |
+
"total_quotes_generated": total_quotes,
|
| 175 |
+
"quotes_by_niche": {niche: len(quotes) for niche, quotes in self.quotes_by_niche.items()},
|
| 176 |
+
"niches_tracked": len(self.quotes_by_niche)
|
| 177 |
}
|
| 178 |
|
| 179 |
+
def clear_history(self, niche: Optional[str] = None):
|
| 180 |
+
"""Clear quote history (use with caution)
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
niche: If provided, clear only this niche. Otherwise clear all.
|
| 184 |
+
"""
|
| 185 |
+
if niche:
|
| 186 |
+
if niche in self.quotes_by_niche:
|
| 187 |
+
self.quotes_by_niche[niche] = []
|
| 188 |
+
else:
|
| 189 |
+
self.quotes_by_niche = {}
|
| 190 |
self._save_history()
|
| 191 |
|
| 192 |
|
|
|
|
| 330 |
stats = generator.get_stats()
|
| 331 |
print("\nStats:")
|
| 332 |
print(f" Total generated: {stats['total_quotes_generated']}")
|
| 333 |
+
print(f" Niches tracked: {stats['niches_tracked']}")
|
| 334 |
+
print(f" Per niche: {stats['quotes_by_niche']}")
|
| 335 |
|
| 336 |
except Exception as e:
|
| 337 |
print(f"Error: {e}")
|
| 338 |
print("\nMake sure GEMINI_API_KEY is set in environment variables")
|
|
|