Spaces:
Sleeping
Sleeping
File size: 18,576 Bytes
edd00ca | 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | import os
import json
import re
from openai import OpenAI
import google.generativeai as genai
from tenacity import retry, stop_after_attempt, wait_exponential
from dotenv import load_dotenv
load_dotenv()
# ============================================================
# API INITIALIZATION
# ============================================================
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
if not PERPLEXITY_API_KEY:
raise ValueError("β PERPLEXITY_API_KEY not set in .env")
if not GEMINI_API_KEY:
raise ValueError("β GEMINI_API_KEY not set in .env")
perplexity_client = OpenAI(
api_key=PERPLEXITY_API_KEY,
base_url="https://api.perplexity.ai",
)
genai.configure(api_key=GEMINI_API_KEY)
# ============================================================
# TECHNICAL PIPELINE
# ============================================================
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def generate_technical_content(topic):
"""
Stage 1: Generate technical slides using Perplexity.
EXACT PROMPT from technical_gcp_image_pipeline-1.ipynb
"""
print(f"\nπ Generating technical content for: {topic}")
try:
system_prompt = f"""You are a domain expert in technology and IT infrastructure with deep knowledge across all technology domains.
Task:
For the topic "{topic}", generate 9 to 10 slides as JSON.
Instructions:
- Write universally applicable content that any technology professional can understand and use.
- Each slide should have an engaging and concise "slide_title" (maximum 6 words).
- "slide_content" must be 3-4 sentences (strictly 40-60 words) with technical depth and practical relevance.
- For the 3 most critical slides ONLY, add "image_description" (strictly 30-40 words) describing specific technical diagrams.
- First slide: Overview explaining why this technology matters universally.
- Last slide: "Further Learning & Documentation" with placeholder for 5 curated URLs.
- Use clear, accessible language. Avoid industry-specific jargon.
- For all other slides, set image_description to null.
Additional Requirement β ALIASES FIELD:
- Generate 6-7 lowercase alternative names/synonyms for "{topic}".
- First alias MUST be the normalized lowercase form of the topic.
- Include abbreviations and common variations.
Output ONLY valid JSON (no code blocks, no markdown):
{{
"topic": "{topic}",
"aliases": ["primary lowercase form", "alias2", "alias3", ...],
"content": [
{{
"slide_title": "...",
"slide_content": "...",
"image_description": "..." or null
}}
],
"urls": [
{{"title": "...", "url": "https://..."}},
...
]
}}
"""
response = perplexity_client.chat.completions.create(
model="sonar-pro",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Generate a universally applicable technical presentation on {topic}"}
],
temperature=0.5,
max_tokens=4000,
timeout=60,
)
content = response.choices[0].message.content
try:
result = json.loads(content)
if 'aliases' not in result:
result['aliases'] = [topic.lower().strip()]
print(f"β
Generation successful - {len(result.get('content', []))} slides")
return result
except json.JSONDecodeError:
json_match = re.search(r'\{.*\}', content, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
if 'aliases' not in result:
result['aliases'] = [topic.lower().strip()]
return result
raise ValueError("Could not parse JSON from response")
except Exception as e:
print(f"β Generation failed: {type(e).__name__}: {str(e)}")
raise
@retry(
stop=stop_after_attempt(2),
wait=wait_exponential(multiplier=1, min=3, max=10)
)
def correct_technical_content(generated_json):
"""
Stage 2: Correct with Gemini 2.5 Flash (TEXT ONLY).
EXACT PROMPT from technical_gcp_image_pipeline-1.ipynb
"""
print(f"\nπ Correcting technical content with Gemini 2.5 Flash")
try:
gemini_model = genai.GenerativeModel("gemini-2.5-flash")
correction_prompt = f"""You are an expert technical editor for universal technology training materials.
Review the following slide presentation and improve it:
{json.dumps(generated_json, indent=2)}
Your tasks:
1. Ensure slide titles are clear, concise (max 6 words) and engaging.
2. Verify that slide_content is universally applicable.
3. Check that content flows logically, is technically accurate.
4. For image_descriptions: Make them specific, actionable, and suitable for technical diagram generation.
5. Review and enhance URLs - add 2-3 additional high-quality URLs if missing.
6. Keep all word counts natural and readable.
CRITICAL INSTRUCTION:
- The field "aliases" must remain EXACTLY as provided (do not change it).
- Keep "image_description" fields exactly as they are.
- For slides without image_description, set to null.
- Retain the most educationally valuable 3 slides for images β set the rest to null.
OUTPUT REQUIREMENT:
Return ONLY the corrected JSON in the exact same schema as the input.
Do not include code fences, markdown, or extra commentary.
"""
response = gemini_model.generate_content(correction_prompt)
corrected_text = response.text.strip()
corrected_text = re.sub(r'^\s*```(?:json)?\s*\n?', '', corrected_text, count=1)
corrected_text = re.sub(r'\s*```\s*$', '', corrected_text, count=1)
try:
result = json.loads(corrected_text)
if 'aliases' not in result:
result['aliases'] = generated_json.get('aliases', [])
print(f"β
Correction successful")
return result
except json.JSONDecodeError:
json_match = re.search(r'\{.*\}', corrected_text, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
if 'aliases' not in result:
result['aliases'] = generated_json.get('aliases', [])
return result
print(f"β οΈ Correction parsing failed - returning original")
return generated_json
except Exception as e:
print(f"β Correction failed: {type(e).__name__}: {str(e)}")
raise
@retry(
stop=stop_after_attempt(2),
wait=wait_exponential(multiplier=1, min=3, max=10)
)
def refine_technical_content(validated_json):
"""
Stage 3: Final refinement with Perplexity.
EXACT PROMPT from technical_gcp_image_pipeline-1.ipynb
"""
print(f"\nπ Refining technical content")
try:
refine_prompt = f"""You are a senior technical content specialist for universal technology training.
This slide presentation has been validated. Perform the final refinement:
{json.dumps(validated_json, indent=2)}
Your tasks:
1. Ensure image_descriptions are detailed, specific, and suitable for technical diagram generation.
2. Verify that slide content is universally applicable and consistent.
3. Confirm that all technical terms are accurate.
4. Review and refine the URLs:
- Select up to 5 of the best URLs only.
- Order them by: Authority, Relevance, Learning value, Diversity.
- Ensure all chosen URLs are authoritative and current.
5. Keep all slide content exactly the same length/style.
6. Maintain perfect JSON structure.
CRITICAL INSTRUCTION:
- The field "aliases" must remain EXACTLY as provided.
- Keep "image_description" fields for image generation.
OUTPUT REQUIREMENT:
Return ONLY the refined JSON in the exact same schema as the input.
"""
response = perplexity_client.chat.completions.create(
model="sonar-pro",
messages=[{"role": "user", "content": refine_prompt}],
temperature=0.3,
max_tokens=4000,
timeout=60,
)
refined_text = response.choices[0].message.content.strip()
refined_text = re.sub(r'^\s*```(?:json)?\s*\n?', '', refined_text, count=1)
refined_text = re.sub(r'\s*```\s*$', '', refined_text, count=1)
try:
result = json.loads(refined_text)
if 'aliases' not in result:
result['aliases'] = validated_json.get('aliases', [])
print(f"β
Refinement successful")
return result
except json.JSONDecodeError:
json_match = re.search(r'\{.*\}', refined_text, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
if 'aliases' not in result:
result['aliases'] = validated_json.get('aliases', [])
return result
print(f"β οΈ Refinement failed - returning validated content")
return validated_json
except Exception as e:
print(f"β Refinement failed: {type(e).__name__}: {str(e)}")
raise
# ============================================================
# OPERATIONAL PIPELINE
# ============================================================
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def generate_operational_content(topic):
"""
Stage 1: Generate operational slides using Perplexity.
EXACT PROMPT from operational_gcp_image_pipeline-2.ipynb
"""
print(f"\nπ Generating operational content for: {topic}")
try:
system_prompt = f"""You are a domain expert in business operations, compliance, regulatory frameworks, and enterprise management.
Task:
For the topic "{topic}", generate 9 to 10 slides as JSON.
Instructions:
- Target intermediate professionals (2+ years experience) seeking actionable, scenario-driven insights.
- Each slide should have a unique and engaging "slide_title" (maximum 6 words).
- "slide_content" must be 3-4 sentences (strictly 40-60 words), balancing regulatory requirements with operational business value.
- Emphasize both regulatory drivers AND business impact: compliance obligations, operational efficiency, risk mitigation, and competitive advantage.
- For the 3 most important slides ONLY, add "image_description" (strictly 30-40 words) describing meaningful business/operational diagrams.
- First slide: Overview positioning the topic's regulatory importance and business operational impact.
- Last slide: "Further Learning & Documentation" with specific next learning topics.
- Use clear, accessible language without basic dictionary definitions.
- Focus on practical application, regulatory compliance, and business outcomes.
- For all other slides, set image_description to null.
Additional Requirement β ALIASES FIELD:
- Generate 4-5 lowercase alternative names/synonyms for "{topic}".
- First alias MUST be the normalized lowercase form of the topic.
- Include abbreviations and terms that refer to the same concept.
Output ONLY valid JSON (no code blocks, no markdown):
{{
"topic": "{topic}",
"aliases": ["primary lowercase form", "alias2", ...],
"content": [
{{
"slide_title": "...",
"slide_content": "...",
"image_description": "..." or null
}}
],
"urls": [
{{"title": "...", "url": "https://..."}},
...
]
}}
"""
response = perplexity_client.chat.completions.create(
model="sonar-pro",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Generate an intermediate-level, practical business operations presentation on: {topic}"}
],
temperature=0.5,
max_tokens=4000,
timeout=60,
)
content = response.choices[0].message.content
try:
result = json.loads(content)
if 'aliases' not in result:
result['aliases'] = [topic.lower().strip()]
print(f"β
Generation successful - {len(result.get('content', []))} slides")
return result
except json.JSONDecodeError:
json_match = re.search(r'\{.*\}', content, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
if 'aliases' not in result:
result['aliases'] = [topic.lower().strip()]
return result
raise ValueError("Could not parse JSON from response")
except Exception as e:
print(f"β Generation failed: {type(e).__name__}: {str(e)}")
raise
@retry(
stop=stop_after_attempt(2),
wait=wait_exponential(multiplier=1, min=3, max=10)
)
def correct_operational_content(generated_json):
"""
Stage 2: Correct with Gemini 2.5 PRO (stronger model for operational).
EXACT PROMPT from operational_gcp_image_pipeline-2.ipynb
"""
print(f"\nπ Correcting operational content with Gemini 2.5 PRO")
try:
gemini_model = genai.GenerativeModel("gemini-2.5-pro") # STRONGER MODEL FOR OPERATIONAL
correction_prompt = f"""You are an expert business operations and compliance editor.
Review this business operations presentation and improve it:
{json.dumps(generated_json, indent=2)}
Your tasks:
1. Ensure slide titles are clear, concise (max 6 words), and business-focused.
2. Verify slide_content balances regulatory requirements WITH business operational value (40β60 words).
3. Strengthen regulatory references: name specific acts, frameworks, or compliance concepts.
4. For image_descriptions: Make them specific to business processes and regulatory workflows.
5. Review and improve the URLs - add 2-3 additional high-quality official URLs.
6. Maintain the intermediate professional tone.
7. Ensure logical flow: regulatory β operational β actionable insights.
CRITICAL INSTRUCTION:
- The field "aliases" must remain EXACTLY as provided.
- Keep "image_description" fields for image generation.
- For slides without image_description, set to null.
- Retain the most important 3 slides for images β set the rest to null.
OUTPUT REQUIREMENT:
Return ONLY the corrected JSON in the exact same schema as the input.
"""
response = gemini_model.generate_content(correction_prompt)
corrected_text = response.text.strip()
corrected_text = re.sub(r'^\s*```(?:json)?\s*\n?', '', corrected_text, count=1)
corrected_text = re.sub(r'\s*```\s*$', '', corrected_text, count=1)
try:
result = json.loads(corrected_text)
if 'aliases' not in result:
result['aliases'] = generated_json.get('aliases', [])
print(f"β
Correction successful")
return result
except json.JSONDecodeError:
json_match = re.search(r'\{.*\}', corrected_text, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
if 'aliases' not in result:
result['aliases'] = generated_json.get('aliases', [])
return result
print(f"β οΈ Correction parsing failed - returning original")
return generated_json
except Exception as e:
print(f"β Correction failed: {type(e).__name__}: {str(e)}")
raise
@retry(
stop=stop_after_attempt(2),
wait=wait_exponential(multiplier=1, min=3, max=10)
)
def refine_operational_content(validated_json):
"""
Stage 3: Final refinement with Perplexity.
EXACT PROMPT from operational_gcp_image_pipeline-2.ipynb
"""
print(f"\nπ Refining operational content")
try:
refine_prompt = f"""You are a senior business operations content specialist.
This business operations presentation has been validated. Perform the final refinement:
{json.dumps(validated_json, indent=2)}
Your tasks:
1. Ensure image descriptions are specific to business workflows, compliance processes, and decision-making.
2. Verify slide content emphasizes actionable business value, regulatory relevance, and measurable outcomes.
3. Confirm terminology is accurate, consistent, and understandable to intermediate business professionals.
4. Review and refine the URLs:
- Select up to 5 of the best URLs only.
- Order by: Authority (regulatory bodies first), Relevance, Learning value, Diversity.
- Ensure all URLs are authoritative, recent, and relevant.
5. Keep all slide content exactly the same.
6. Maintain perfect JSON structure.
CRITICAL INSTRUCTION:
- The field "aliases" must remain EXACTLY as provided.
- Keep "image_description" fields for image generation.
OUTPUT REQUIREMENT:
Return ONLY the refined JSON in the exact same schema as the input.
"""
response = perplexity_client.chat.completions.create(
model="sonar-pro",
messages=[{"role": "user", "content": refine_prompt}],
temperature=0.3,
max_tokens=4000,
timeout=60,
)
refined_text = response.choices[0].message.content.strip()
refined_text = re.sub(r'^\s*```(?:json)?\s*\n?', '', refined_text, count=1)
refined_text = re.sub(r'\s*```\s*$', '', refined_text, count=1)
try:
result = json.loads(refined_text)
if 'aliases' not in result:
result['aliases'] = validated_json.get('aliases', [])
print(f"β
Refinement successful")
return result
except json.JSONDecodeError:
json_match = re.search(r'\{.*\}', refined_text, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
if 'aliases' not in result:
result['aliases'] = validated_json.get('aliases', [])
return result
print(f"β οΈ Refinement failed - returning validated content")
return validated_json
except Exception as e:
print(f"β Refinement failed: {type(e).__name__}: {str(e)}")
raise
print("β All pipeline functions loaded (Perplexity + Gemini 2.5 Flash/Pro for text)")
|