Spaces:
Running
Running
File size: 3,079 Bytes
fa22010 | 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 | import sys
import re
file = 'content/generator.py'
with open(file, 'r', encoding='utf-8') as f:
code = f.read()
code = code.replace('from groq import AsyncGroq', 'import google.generativeai as genai\nfrom google.generativeai.types import GenerationConfig')
code = code.replace('GROQ_API_KEY, GROQ_MODEL, GROQ_MAX_TOKENS,', 'GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS,')
code = code.replace('GROQ_TEMPERATURE, SUBJECT_ROTATION', 'GEMINI_TEMPERATURE, SUBJECT_ROTATION')
code = code.replace('# Initialize Groq Client\nclient = AsyncGroq(api_key=GROQ_API_KEY)', '# Initialize Gemini Client\ngenai.configure(api_key=GEMINI_API_KEY)')
code = code.replace('_call_groq', '_call_gemini')
old_func_pattern = re.compile(r'async def _call_gemini\(prompt: str\) -> str:.*?(?=\ndef _channel_subjects)', re.DOTALL)
new_func = """async def _call_gemini(prompt: str) -> str:
\"\"\"Wrapper for Gemini API calls with retry logic for rate limits.\"\"\"
max_retries = 3
base_delay = 2 # Gemini free tier might need some delay on rate limits
for attempt in range(max_retries):
try:
model = genai.GenerativeModel(
model_name=GEMINI_MODEL,
system_instruction=template_manager.system_prompt
)
response = await model.generate_content_async(
prompt,
generation_config=GenerationConfig(
max_output_tokens=GEMINI_MAX_TOKENS,
temperature=GEMINI_TEMPERATURE,
)
)
content = response.text
if not content:
logger.warning(f"Gemini returned empty response (Attempt {attempt+1}/{max_retries})")
if attempt < max_retries - 1:
await asyncio.sleep(base_delay * (2 ** attempt))
continue
return None
return _clean_markdown(content.strip())
except Exception as e:
err_msg = str(e).lower()
# Handle rate limits
if "429" in err_msg or "quota" in err_msg or "rate" in err_msg:
wait_time = base_delay * (2 ** attempt) + 2
logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
if attempt < max_retries - 1:
import asyncio
await asyncio.sleep(wait_time)
continue
logger.error(f"Gemini API error: {e}\\n{traceback.format_exc()}")
return None
return None
"""
code = old_func_pattern.sub(new_func, code)
# Fix remaining Groq terms in logging/comments EXCEPT in imports if any
code = code.replace('Groq', 'Gemini').replace('groq', 'gemini')
code = code.replace('import google.geminiativeai as genai', 'import google.generativeai as genai')
code = code.replace('from google.geminiativeai.types', 'from google.generativeai.types')
with open(file, 'w', encoding='utf-8') as f:
f.write(code)
print("generator.py refactored!")
|