Spaces:
Sleeping
Sleeping
Update utils/llm_client.py
Browse files- utils/llm_client.py +608 -603
utils/llm_client.py
CHANGED
|
@@ -1,603 +1,608 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Pundit Feynman LLM Client β 3-Stage Pipeline
|
| 3 |
-
Stage 1: Analyze (images β structured JSON analysis)
|
| 4 |
-
Stage 2: Design (analysis β implementation plan JSON)
|
| 5 |
-
Stage 3: Generate (analysis + design β notebook cells JSON)
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
import os
|
| 9 |
-
import json
|
| 10 |
-
import time
|
| 11 |
-
import re
|
| 12 |
-
import requests
|
| 13 |
-
from openai import OpenAI
|
| 14 |
-
from dotenv import load_dotenv
|
| 15 |
-
|
| 16 |
-
load_dotenv()
|
| 17 |
-
|
| 18 |
-
# ββ Configuration ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
-
API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 20 |
-
BASE_URL = os.getenv("NVIDIA_BASE_URL", "https://integrate.api.nvidia.com/v1")
|
| 21 |
-
MODEL = os.getenv("LLM_MODEL", "qwen/qwen3.5-397b-a17b")
|
| 22 |
-
MAX_IMAGES_PER_REQUEST = int(os.getenv("MAX_IMAGES_PER_REQUEST", "8"))
|
| 23 |
-
|
| 24 |
-
# OCR Configuration
|
| 25 |
-
OCR_API_KEY = os.getenv("NVIDIA_OCR_API_KEY", "")
|
| 26 |
-
OCR_API_URL = "https://ai.api.nvidia.com/v1/cv/nvidia/nemoretriever-ocr-v1"
|
| 27 |
-
|
| 28 |
-
# FLUX.1-schnell Image Generation
|
| 29 |
-
FLUX_API_KEY = os.getenv("NVIDIA_FLUX_API_KEY", "")
|
| 30 |
-
FLUX_API_URL = "https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell"
|
| 31 |
-
|
| 32 |
-
MAX_RETRIES = 3
|
| 33 |
-
RETRY_DELAYS = [5, 15, 30]
|
| 34 |
-
|
| 35 |
-
client = OpenAI(
|
| 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 |
-
{"section": "
|
| 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 |
-
f"{
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
if repaired
|
| 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 |
-
yield ("text", "
|
| 481 |
-
yield ("text", "
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
yield ("
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
"""
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
"
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
"
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
"
|
| 580 |
-
"
|
| 581 |
-
"
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
if
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pundit Feynman LLM Client β 3-Stage Pipeline
|
| 3 |
+
Stage 1: Analyze (images β structured JSON analysis)
|
| 4 |
+
Stage 2: Design (analysis β implementation plan JSON)
|
| 5 |
+
Stage 3: Generate (analysis + design β notebook cells JSON)
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
import re
|
| 12 |
+
import requests
|
| 13 |
+
from openai import OpenAI
|
| 14 |
+
from dotenv import load_dotenv
|
| 15 |
+
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
# ββ Configuration ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
+
API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 20 |
+
BASE_URL = os.getenv("NVIDIA_BASE_URL", "https://integrate.api.nvidia.com/v1")
|
| 21 |
+
MODEL = os.getenv("LLM_MODEL", "qwen/qwen3.5-397b-a17b")
|
| 22 |
+
MAX_IMAGES_PER_REQUEST = int(os.getenv("MAX_IMAGES_PER_REQUEST", "8"))
|
| 23 |
+
|
| 24 |
+
# OCR Configuration
|
| 25 |
+
OCR_API_KEY = os.getenv("NVIDIA_OCR_API_KEY", "")
|
| 26 |
+
OCR_API_URL = "https://ai.api.nvidia.com/v1/cv/nvidia/nemoretriever-ocr-v1"
|
| 27 |
+
|
| 28 |
+
# FLUX.1-schnell Image Generation
|
| 29 |
+
FLUX_API_KEY = os.getenv("NVIDIA_FLUX_API_KEY", "")
|
| 30 |
+
FLUX_API_URL = "https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell"
|
| 31 |
+
|
| 32 |
+
MAX_RETRIES = 3
|
| 33 |
+
RETRY_DELAYS = [5, 15, 30]
|
| 34 |
+
|
| 35 |
+
client = OpenAI(
|
| 36 |
+
base_url=BASE_URL,
|
| 37 |
+
api_key=API_KEY,
|
| 38 |
+
timeout=600.0, # Explicit default timeout for the client
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ββ Prompts ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 43 |
+
|
| 44 |
+
SYSTEM_PROMPT = (
|
| 45 |
+
"You are an expert research engineer and educator who converts academic papers into "
|
| 46 |
+
"clear, educational, executable Python code. You produce structured JSON output for "
|
| 47 |
+
"each stage of the pipeline. When building toy implementations, you create REAL working code "
|
| 48 |
+
"(PyTorch, Transformer layers, actual training loops) at reduced scale that "
|
| 49 |
+
"runs on CPU. You prioritize faithful replication of the paper's architecture "
|
| 50 |
+
"and algorithms while making the code deeply educational with clear explanations, "
|
| 51 |
+
"using the Feynman technique to break down complex math into simple analogies, "
|
| 52 |
+
"verbose logging, and insightful visualizations."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
ANALYSIS_PROMPT = """Analyze this research paper text and return a JSON object with:
|
| 56 |
+
{
|
| 57 |
+
"title": "exact paper title",
|
| 58 |
+
"authors": ["author names"],
|
| 59 |
+
"research_field": "e.g. NLP, Computer Vision, RL",
|
| 60 |
+
"abstract_summary": "2-3 sentence plain English summary of the paper",
|
| 61 |
+
"feynman_analogy": "A brilliant, everyday analogy that maps perfectly to the paper's core key_insight (e.g., comparing attention mechanisms to a cocktail party)",
|
| 62 |
+
"feynman_core_concept": "Explain the paper's main idea as if teaching a bright 12-year-old, using the analogy above, in 3-5 sentences",
|
| 63 |
+
"key_insight": "the core novel contribution in one sentence",
|
| 64 |
+
"algorithms": [
|
| 65 |
+
{
|
| 66 |
+
"name": "algorithm name",
|
| 67 |
+
"purpose": "what it does",
|
| 68 |
+
"key_equations": ["important formulas in LaTeX notation"],
|
| 69 |
+
"pseudocode_steps": ["step1", "step2"]
|
| 70 |
+
}
|
| 71 |
+
],
|
| 72 |
+
"architecture": {
|
| 73 |
+
"type": "e.g. Transformer, CNN, GAN",
|
| 74 |
+
"components": ["list of main components"],
|
| 75 |
+
"data_flow": "description of how data flows through the model"
|
| 76 |
+
},
|
| 77 |
+
"datasets_mentioned": ["dataset names"],
|
| 78 |
+
"implementation_requirements": {
|
| 79 |
+
"frameworks": ["PyTorch"],
|
| 80 |
+
"key_hyperparameters": {"param": "value"},
|
| 81 |
+
"estimated_complexity": "low/medium/high for toy version"
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
Return ONLY valid JSON, no markdown, no extra text."""
|
| 86 |
+
|
| 87 |
+
DESIGN_PROMPT = """Based on this paper analysis, create a toy implementation design that runs on CPU.
|
| 88 |
+
Return a JSON object with:
|
| 89 |
+
{
|
| 90 |
+
"model_architecture": {
|
| 91 |
+
"type": "architecture type",
|
| 92 |
+
"embed_dim": 64,
|
| 93 |
+
"num_layers": 2,
|
| 94 |
+
"num_heads": 4,
|
| 95 |
+
"vocab_size": 1000,
|
| 96 |
+
"max_seq_len": 64,
|
| 97 |
+
"components": [
|
| 98 |
+
{
|
| 99 |
+
"name": "component name",
|
| 100 |
+
"class_name": "PythonClassName",
|
| 101 |
+
"description": "what this component does",
|
| 102 |
+
"key_params": {"param": "value"}
|
| 103 |
+
}
|
| 104 |
+
]
|
| 105 |
+
},
|
| 106 |
+
"training_config": {
|
| 107 |
+
"optimizer": "Adam",
|
| 108 |
+
"learning_rate": 0.001,
|
| 109 |
+
"num_epochs": 5,
|
| 110 |
+
"batch_size": 16,
|
| 111 |
+
"loss_function": "CrossEntropyLoss",
|
| 112 |
+
"dataset_strategy": "synthetic generation approach"
|
| 113 |
+
},
|
| 114 |
+
"visualization_plan": [
|
| 115 |
+
"loss curve",
|
| 116 |
+
"attention heatmap",
|
| 117 |
+
"sample predictions"
|
| 118 |
+
],
|
| 119 |
+
"estimated_cells": 15,
|
| 120 |
+
"code_structure": [
|
| 121 |
+
{"section": "imports", "description": "required libraries"},
|
| 122 |
+
{"section": "model", "description": "model architecture classes"},
|
| 123 |
+
{"section": "data", "description": "synthetic data generation"},
|
| 124 |
+
{"section": "training", "description": "training loop"},
|
| 125 |
+
{"section": "evaluation", "description": "testing and visualization"}
|
| 126 |
+
]
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
Return ONLY valid JSON, no markdown, no extra text."""
|
| 130 |
+
|
| 131 |
+
GENERATE_PROMPT_TEMPLATE = """You are generating a Jupyter notebook from a paper analysis and implementation design.
|
| 132 |
+
Analysis: {analysis}
|
| 133 |
+
Design: {design}
|
| 134 |
+
|
| 135 |
+
Note: You are a 397B parameter model (Qwen 3.5) with 17B actively used parameters (MoE architecture).
|
| 136 |
+
This means you have deep expertise and vast knowledge. Use it to produce genuinely educational content.
|
| 137 |
+
|
| 138 |
+
Return a JSON array of notebook cells following this **exact 13-section structure**:
|
| 139 |
+
|
| 140 |
+
1. **Title & Overview** (markdown) β Paper title, authors, a one-paragraph summary of the paper.
|
| 141 |
+
|
| 142 |
+
2. **Table of Contents** (markdown) β Numbered list of all 13 sections. Each section name should be a clickable anchor link.
|
| 143 |
+
|
| 144 |
+
3. **The Feynman Explanation** (markdown) β A step-by-step explanation of the WHOLE paper using the Feynman technique. Break down the core algorithms, math, and architecture into the absolute simplest terms possible. Expand heavily on the `feynman_analogy` and `feynman_core_concept` from the analysis. Use relatable, everyday analogies for each major step so a beginner can intuitively grasp how the system works before seeing the code.
|
| 145 |
+
|
| 146 |
+
4. **Environment Setup** (code) β pip installs and imports. Include `torch`, `numpy`, `matplotlib`, and any other needed libraries.
|
| 147 |
+
|
| 148 |
+
5. **Configuration & Hyperparameters** (code) β A single config dict or dataclass with all hyperparameters. Add comments explaining each.
|
| 149 |
+
|
| 150 |
+
6. **Data Preparation** (code) β Synthetic dataset generation or loading. Must produce realistic dummy data matching the paper's domain.
|
| 151 |
+
|
| 152 |
+
7. **Model Architecture** (code) β Full PyTorch model implementation. Use `nn.Module` subclasses with detailed docstrings about each component. Include shape comments.
|
| 153 |
+
|
| 154 |
+
8. **Training Loop** (code) β Complete training loop with loss tracking, progress printing, and gradient clipping.
|
| 155 |
+
|
| 156 |
+
9. **Training Execution** (code) β Run the training and display results.
|
| 157 |
+
|
| 158 |
+
10. **Evaluation & Metrics** (code) β Run inference on test data and compute relevant metrics.
|
| 159 |
+
|
| 160 |
+
11. **Visualizations** (code) β Matplotlib charts: loss curves, attention heatmaps or feature maps, sample predictions.
|
| 161 |
+
|
| 162 |
+
12. **Key Takeaways** (markdown) β Bullet-point summary of what was learned, what would change at full scale, potential improvements.
|
| 163 |
+
|
| 164 |
+
13. **References** (markdown) β Paper citation, related work links, library documentation links.
|
| 165 |
+
|
| 166 |
+
Each cell in the JSON array must have:
|
| 167 |
+
{{"cell_type": "code" or "markdown", "source": "cell content as a string"}}
|
| 168 |
+
|
| 169 |
+
RULES:
|
| 170 |
+
- All code must be executable on CPU
|
| 171 |
+
- Use educational variable names and heavy commenting
|
| 172 |
+
- Include print() statements showing tensor shapes and intermediate results
|
| 173 |
+
- Follow the 13-section structure exactly
|
| 174 |
+
- Minimum 15 cells total
|
| 175 |
+
- The Feynman Explanation should be at least 300 words
|
| 176 |
+
- Return ONLY the JSON array, no markdown fences"""
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ββ OCR extraction (NVIDIA NeMo Retriever OCR v1) βββββββββββββββββββββββββ
|
| 180 |
+
|
| 181 |
+
def extract_text_from_images(base64_images):
|
| 182 |
+
"""Extract text from paper page images using NVIDIA NeMo Retriever OCR API.
|
| 183 |
+
Sends page images to the dedicated OCR model for fast, accurate extraction.
|
| 184 |
+
Falls back to page-by-page if a batch request fails.
|
| 185 |
+
"""
|
| 186 |
+
all_text = []
|
| 187 |
+
headers = {
|
| 188 |
+
"Authorization": f"Bearer {OCR_API_KEY}",
|
| 189 |
+
"Accept": "application/json",
|
| 190 |
+
"Content-Type": "application/json",
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
total = len(base64_images)
|
| 194 |
+
print(f" OCR: Processing {total} pages via NVIDIA NeMo Retriever...")
|
| 195 |
+
|
| 196 |
+
for page_idx, img_b64 in enumerate(base64_images):
|
| 197 |
+
print(f" Page {page_idx + 1}/{total}...")
|
| 198 |
+
|
| 199 |
+
payload = {
|
| 200 |
+
"input": [
|
| 201 |
+
{
|
| 202 |
+
"type": "image_url",
|
| 203 |
+
"url": f"data:image/jpeg;base64,{img_b64}"
|
| 204 |
+
}
|
| 205 |
+
],
|
| 206 |
+
"merge_levels": ["paragraph"]
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
try:
|
| 210 |
+
resp = requests.post(
|
| 211 |
+
OCR_API_URL,
|
| 212 |
+
headers=headers,
|
| 213 |
+
json=payload,
|
| 214 |
+
timeout=60,
|
| 215 |
+
)
|
| 216 |
+
resp.raise_for_status()
|
| 217 |
+
result = resp.json()
|
| 218 |
+
|
| 219 |
+
# Extract text from OCR response
|
| 220 |
+
page_text = _parse_ocr_response(result, page_idx + 1)
|
| 221 |
+
if page_text:
|
| 222 |
+
all_text.append(page_text)
|
| 223 |
+
|
| 224 |
+
except Exception as e:
|
| 225 |
+
print(f" \u26a0 OCR failed for page {page_idx + 1}: {e}")
|
| 226 |
+
# Continue with remaining pages
|
| 227 |
+
continue
|
| 228 |
+
|
| 229 |
+
if not all_text:
|
| 230 |
+
raise RuntimeError("OCR failed: No text extracted from any page")
|
| 231 |
+
|
| 232 |
+
combined = "\n\n".join(all_text)
|
| 233 |
+
print(f" OCR complete: {len(combined)} chars from {len(all_text)}/{total} pages")
|
| 234 |
+
return combined
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _parse_ocr_response(response_json, page_num):
|
| 238 |
+
"""Parse the NVIDIA OCR API response into clean text.
|
| 239 |
+
Response format: {"data": [{"text_detections": [{"text_prediction": {"text": ..., "confidence": ...}}]}]}
|
| 240 |
+
"""
|
| 241 |
+
texts = []
|
| 242 |
+
try:
|
| 243 |
+
for item in response_json.get("data", []):
|
| 244 |
+
for detection in item.get("text_detections", []):
|
| 245 |
+
pred = detection.get("text_prediction", {})
|
| 246 |
+
text = pred.get("text", "").strip()
|
| 247 |
+
confidence = pred.get("confidence", 0)
|
| 248 |
+
# Only include text with reasonable confidence
|
| 249 |
+
if text and confidence > 0.3:
|
| 250 |
+
texts.append(text)
|
| 251 |
+
except Exception as e:
|
| 252 |
+
print(f" \u26a0 Error parsing OCR response for page {page_num}: {e}")
|
| 253 |
+
return ""
|
| 254 |
+
|
| 255 |
+
return "\n".join(texts)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# ββ LLM Call with Retry βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 259 |
+
|
| 260 |
+
def call_with_retry(messages, max_tokens=4096, temperature=0.3, stream=False):
|
| 261 |
+
"""Call the LLM API with retry logic for transient errors."""
|
| 262 |
+
last_error = None
|
| 263 |
+
|
| 264 |
+
for attempt in range(MAX_RETRIES):
|
| 265 |
+
try:
|
| 266 |
+
kwargs = dict(
|
| 267 |
+
model=MODEL,
|
| 268 |
+
messages=messages,
|
| 269 |
+
max_tokens=max_tokens,
|
| 270 |
+
temperature=temperature,
|
| 271 |
+
timeout=300,
|
| 272 |
+
)
|
| 273 |
+
if stream:
|
| 274 |
+
kwargs["stream"] = True
|
| 275 |
+
return client.chat.completions.create(**kwargs)
|
| 276 |
+
else:
|
| 277 |
+
response = client.chat.completions.create(**kwargs)
|
| 278 |
+
return response.choices[0].message.content
|
| 279 |
+
|
| 280 |
+
except Exception as e:
|
| 281 |
+
error_str = str(e).lower()
|
| 282 |
+
# Include "timeout" and "timed out" in retryable errors
|
| 283 |
+
if any(kw in error_str for kw in ["429", "rate", "500", "503", "overloaded", "unavailable", "timeout", "timed out"]):
|
| 284 |
+
last_error = e
|
| 285 |
+
wait = RETRY_DELAYS[min(attempt, len(RETRY_DELAYS) - 1)]
|
| 286 |
+
print(f" β Transient error: {e}. Waiting {wait}s before retry {attempt + 1}/{MAX_RETRIES}...")
|
| 287 |
+
time.sleep(wait)
|
| 288 |
+
else:
|
| 289 |
+
raise
|
| 290 |
+
|
| 291 |
+
raise RuntimeError(f"Failed after {MAX_RETRIES} retries. Last error: {last_error}")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ββ JSON Parsing ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
|
| 296 |
+
def parse_llm_json(raw_text, step_name):
|
| 297 |
+
"""Parse JSON from LLM response, with cleanup and one repair attempt."""
|
| 298 |
+
if raw_text is None:
|
| 299 |
+
print(f" β LLM returned None for {step_name}")
|
| 300 |
+
return {}
|
| 301 |
+
text = raw_text.strip()
|
| 302 |
+
|
| 303 |
+
# Strip markdown code fences if present
|
| 304 |
+
if text.startswith("```"):
|
| 305 |
+
first_newline = text.index("\n")
|
| 306 |
+
text = text[first_newline + 1:]
|
| 307 |
+
if text.endswith("```"):
|
| 308 |
+
text = text[:-3]
|
| 309 |
+
text = text.strip()
|
| 310 |
+
|
| 311 |
+
# Try direct parse
|
| 312 |
+
try:
|
| 313 |
+
return json.loads(text)
|
| 314 |
+
except json.JSONDecodeError as e:
|
| 315 |
+
print(f" β JSON parse failed in {step_name}. Attempting repair...")
|
| 316 |
+
|
| 317 |
+
# Attempt auto-repair via LLM
|
| 318 |
+
repair_prompt = (
|
| 319 |
+
f"The following text was supposed to be valid JSON but has a syntax error:\n\n"
|
| 320 |
+
f"{text[:6000]}\n\n"
|
| 321 |
+
f"Error: {e}\n\n"
|
| 322 |
+
f"Return ONLY the corrected valid JSON, nothing else."
|
| 323 |
+
)
|
| 324 |
+
repaired = call_with_retry(
|
| 325 |
+
messages=[
|
| 326 |
+
{"role": "system", "content": "You are a JSON repair tool. Return only valid JSON."},
|
| 327 |
+
{"role": "user", "content": repair_prompt},
|
| 328 |
+
],
|
| 329 |
+
max_tokens=max(len(text) // 2, 4096),
|
| 330 |
+
temperature=0.1,
|
| 331 |
+
)
|
| 332 |
+
if repaired is None:
|
| 333 |
+
raise ValueError(f"Could not repair JSON from {step_name} β LLM returned None")
|
| 334 |
+
repaired = repaired.strip()
|
| 335 |
+
if repaired.startswith("```"):
|
| 336 |
+
repaired = repaired.split("\n", 1)[1]
|
| 337 |
+
if repaired.endswith("```"):
|
| 338 |
+
repaired = repaired[:-3]
|
| 339 |
+
|
| 340 |
+
try:
|
| 341 |
+
return json.loads(repaired.strip())
|
| 342 |
+
except json.JSONDecodeError:
|
| 343 |
+
# Last resort: try to extract JSON from the text
|
| 344 |
+
json_match = re.search(r'[\[{].*[\]}]', repaired.strip(), re.DOTALL)
|
| 345 |
+
if json_match:
|
| 346 |
+
return json.loads(json_match.group())
|
| 347 |
+
raise ValueError(f"Could not parse JSON from {step_name} even after repair.")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# ββ Pipeline Stages βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 351 |
+
|
| 352 |
+
def analyze_paper(raw_text):
|
| 353 |
+
"""Stage 1: Analyze extracted text into structured JSON."""
|
| 354 |
+
messages = [
|
| 355 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 356 |
+
{"role": "user", "content": f"{ANALYSIS_PROMPT}\n\n--- EXTRACTED PAPER TEXT ---\n\n{raw_text}"},
|
| 357 |
+
]
|
| 358 |
+
raw = call_with_retry(messages, max_tokens=6144, temperature=0.2)
|
| 359 |
+
return parse_llm_json(raw, "paper_analysis")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def design_implementation(analysis):
|
| 363 |
+
"""Stage 2: Create implementation design from analysis."""
|
| 364 |
+
messages = [
|
| 365 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 366 |
+
{"role": "user", "content": f"{DESIGN_PROMPT}\n\n--- PAPER ANALYSIS ---\n\n{json.dumps(analysis, indent=2)}"},
|
| 367 |
+
]
|
| 368 |
+
raw = call_with_retry(messages, max_tokens=6144, temperature=0.2)
|
| 369 |
+
return parse_llm_json(raw, "implementation_design")
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def generate_notebook_cells_stream(analysis, design):
|
| 373 |
+
"""
|
| 374 |
+
Stage 3: Generate notebook cells from analysis and design.
|
| 375 |
+
Yields tokens from the LLM for live streaming in the UI.
|
| 376 |
+
Finally yields the parsed cells list.
|
| 377 |
+
"""
|
| 378 |
+
prompt = GENERATE_PROMPT_TEMPLATE.format(
|
| 379 |
+
analysis=json.dumps(analysis, indent=2),
|
| 380 |
+
design=json.dumps(design, indent=2),
|
| 381 |
+
)
|
| 382 |
+
messages = [
|
| 383 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 384 |
+
{"role": "user", "content": prompt},
|
| 385 |
+
]
|
| 386 |
+
|
| 387 |
+
# Use streaming mode
|
| 388 |
+
stream = call_with_retry(messages, max_tokens=65536, temperature=0.3, stream=True)
|
| 389 |
+
full_response = []
|
| 390 |
+
|
| 391 |
+
for chunk in stream:
|
| 392 |
+
if chunk.choices and chunk.choices[0].delta.content:
|
| 393 |
+
token = chunk.choices[0].delta.content
|
| 394 |
+
full_response.append(token)
|
| 395 |
+
yield ("token", token)
|
| 396 |
+
|
| 397 |
+
raw_text = "".join(full_response)
|
| 398 |
+
result = parse_llm_json(raw_text, "notebook_cells")
|
| 399 |
+
|
| 400 |
+
# Final logic to ensure we return a list of cells
|
| 401 |
+
cells = []
|
| 402 |
+
if isinstance(result, dict):
|
| 403 |
+
cells = result.get("cells", [{"cell_type": "markdown", "source": json.dumps(result, indent=2)}])
|
| 404 |
+
elif isinstance(result, list):
|
| 405 |
+
cells = result
|
| 406 |
+
else:
|
| 407 |
+
cells = [{"cell_type": "markdown", "source": raw_text}]
|
| 408 |
+
|
| 409 |
+
yield ("cells_final", cells)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# ββ Streaming Pipeline βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 413 |
+
|
| 414 |
+
def run_full_pipeline_stream(raw_text):
|
| 415 |
+
"""
|
| 416 |
+
Orchestrates the full 3-stage pipeline.
|
| 417 |
+
Yields SSE-formatted text events for the frontend code viewer.
|
| 418 |
+
Returns final cells via the 'cells' key in the last event.
|
| 419 |
+
|
| 420 |
+
Yields tuples of (event_type, data):
|
| 421 |
+
("text", str) β display text for the code viewer
|
| 422 |
+
("cells", list) β final cells (only yielded once at end)
|
| 423 |
+
("analysis", dict) β analysis metadata
|
| 424 |
+
("error", str) β error message
|
| 425 |
+
"""
|
| 426 |
+
try:
|
| 427 |
+
# ββ Stage 1: Analyze ββ
|
| 428 |
+
yield ("text", "\n Analyzing Paper\n")
|
| 429 |
+
yield ("text", " " + "β" * 40 + "\n\n")
|
| 430 |
+
|
| 431 |
+
analysis = analyze_paper(raw_text)
|
| 432 |
+
|
| 433 |
+
if not analysis:
|
| 434 |
+
yield ("text", " Analysis returned empty. The LLM may have failed.\n\n")
|
| 435 |
+
yield ("error", "Analysis returned empty result")
|
| 436 |
+
return
|
| 437 |
+
|
| 438 |
+
title = analysis.get("title", "Unknown Paper")
|
| 439 |
+
field = analysis.get("research_field", "")
|
| 440 |
+
insight = analysis.get("key_insight", "")
|
| 441 |
+
algos = [a.get("name", "") for a in analysis.get("algorithms", [])]
|
| 442 |
+
feynman_analogy = analysis.get("feynman_analogy", "")
|
| 443 |
+
feynman_concept = analysis.get("feynman_core_concept", "")
|
| 444 |
+
|
| 445 |
+
# Clean, minimal analysis output
|
| 446 |
+
yield ("text", f" {title}\n")
|
| 447 |
+
yield ("text", f" {field}\n\n")
|
| 448 |
+
|
| 449 |
+
# The Feynman Explanation β the star of the show
|
| 450 |
+
if feynman_analogy or feynman_concept:
|
| 451 |
+
yield ("text", " βββ The Feynman Explanation βββ\n\n")
|
| 452 |
+
if feynman_analogy:
|
| 453 |
+
yield ("text", f" {feynman_analogy}\n\n")
|
| 454 |
+
if feynman_concept:
|
| 455 |
+
yield ("text", f" {feynman_concept}\n\n")
|
| 456 |
+
|
| 457 |
+
if insight:
|
| 458 |
+
yield ("text", f" Key Insight: {insight}\n\n")
|
| 459 |
+
|
| 460 |
+
yield ("text", " Analysis complete.\n\n")
|
| 461 |
+
|
| 462 |
+
yield ("analysis", {
|
| 463 |
+
"title": title,
|
| 464 |
+
"field": field,
|
| 465 |
+
"insight": insight,
|
| 466 |
+
"algorithms": algos,
|
| 467 |
+
"feynman_analogy": feynman_analogy,
|
| 468 |
+
})
|
| 469 |
+
|
| 470 |
+
# ββ Stage 2: Design ββ
|
| 471 |
+
yield ("text", "\n Designing Implementation\n")
|
| 472 |
+
yield ("text", " " + "β" * 40 + "\n\n")
|
| 473 |
+
|
| 474 |
+
design = design_implementation(analysis)
|
| 475 |
+
if not design:
|
| 476 |
+
design = {}
|
| 477 |
+
|
| 478 |
+
arch = design.get("model_architecture", {})
|
| 479 |
+
tc = design.get("training_config", {})
|
| 480 |
+
yield ("text", f" Architecture: {arch.get('type', 'N/A')}\n")
|
| 481 |
+
yield ("text", f" Training: {tc.get('optimizer', 'Adam')}, lr={tc.get('learning_rate', 0.001)}, {tc.get('num_epochs', 10)} epochs\n")
|
| 482 |
+
yield ("text", " Design complete.\n\n")
|
| 483 |
+
|
| 484 |
+
# ββ Stage 3: Generate (Now with LIVE STREAMING) ββ
|
| 485 |
+
yield ("text", "\n Generating Notebook (Live Streaming)\n")
|
| 486 |
+
yield ("text", " " + "β" * 40 + "\n\n")
|
| 487 |
+
|
| 488 |
+
cells = []
|
| 489 |
+
for event_type, data in generate_notebook_cells_stream(analysis, design):
|
| 490 |
+
if event_type == "token":
|
| 491 |
+
# Yield raw tokens to the code viewer for "ghost-writing" effect
|
| 492 |
+
yield ("text", data)
|
| 493 |
+
elif event_type == "cells_final":
|
| 494 |
+
cells = data
|
| 495 |
+
|
| 496 |
+
code_cells = sum(1 for c in cells if c.get("cell_type") == "code")
|
| 497 |
+
md_cells = sum(1 for c in cells if c.get("cell_type") == "markdown")
|
| 498 |
+
yield ("text", f"\n\n β
Generation complete: {len(cells)} cells ({code_cells} code, {md_cells} markdown)\n")
|
| 499 |
+
yield ("text", " Notebook ready for download.\n")
|
| 500 |
+
|
| 501 |
+
yield ("cells", cells)
|
| 502 |
+
|
| 503 |
+
except Exception as e:
|
| 504 |
+
yield ("error", str(e))
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
# ββ Legacy compatibility βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 508 |
+
# Keep old function signatures working for backward compatibility
|
| 509 |
+
|
| 510 |
+
def extract_methodology(base64_images):
|
| 511 |
+
"""Legacy wrapper: extracts text from images."""
|
| 512 |
+
return extract_text_from_images(base64_images)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
# ββ Visual Illustration (FLUX.1-schnell) βββββββββββββββββββββββββββββββββββ
|
| 516 |
+
|
| 517 |
+
# System prompt for Qwen to craft image generation prompts
|
| 518 |
+
IMAGE_PROMPT_SYSTEM = """You are a world-class scientific illustrator and prompt engineer.
|
| 519 |
+
Your job: given a structured analysis of a research paper, write ONE prompt for an
|
| 520 |
+
AI image generator (FLUX) that will produce a clear, beautiful, academic-quality
|
| 521 |
+
visual illustration of the paper's CORE CONCEPT.
|
| 522 |
+
|
| 523 |
+
Rules:
|
| 524 |
+
1. Focus on the MAIN IDEA β the central algorithm, architecture, or mechanism.
|
| 525 |
+
2. Describe the visual layout precisely: shapes, arrows, labels, flow direction.
|
| 526 |
+
3. Use academic illustration style: clean lines, labeled components, white background.
|
| 527 |
+
4. Include spatial relationships: "on the left", "flowing into", "surrounded by".
|
| 528 |
+
5. Mention color coding for different components.
|
| 529 |
+
6. Do NOT include text/equations in the image β focus on visual metaphors.
|
| 530 |
+
7. Keep it to ONE paragraph, 80-120 words.
|
| 531 |
+
8. End with style keywords: "scientific diagram, educational poster, vector style,
|
| 532 |
+
clean layout, professional, high resolution"
|
| 533 |
+
|
| 534 |
+
Return ONLY the prompt text, nothing else."""
|
| 535 |
+
|
| 536 |
+
def generate_concept_image(analysis):
|
| 537 |
+
"""
|
| 538 |
+
Generate a visual illustration of a paper's core concept.
|
| 539 |
+
Step 1: Qwen crafts a detailed, structured prompt from the analysis.
|
| 540 |
+
Step 2: FLUX.1-schnell generates the image.
|
| 541 |
+
Returns base64-encoded PNG string or None on failure.
|
| 542 |
+
"""
|
| 543 |
+
if not FLUX_API_KEY:
|
| 544 |
+
raise RuntimeError("NVIDIA_FLUX_API_KEY not set")
|
| 545 |
+
|
| 546 |
+
# ββ Step 1: Qwen β Image Prompt ββ
|
| 547 |
+
analysis_summary = json.dumps({
|
| 548 |
+
"title": analysis.get("title", ""),
|
| 549 |
+
"research_field": analysis.get("research_field") or analysis.get("field", ""),
|
| 550 |
+
"key_insight": analysis.get("key_insight") or analysis.get("insight", ""),
|
| 551 |
+
"algorithms": analysis.get("algorithms", []),
|
| 552 |
+
"feynman_analogy": analysis.get("feynman_analogy", ""),
|
| 553 |
+
"feynman_core_concept": analysis.get("feynman_core_concept", ""),
|
| 554 |
+
}, indent=2)
|
| 555 |
+
|
| 556 |
+
prompt_messages = [
|
| 557 |
+
{"role": "system", "content": IMAGE_PROMPT_SYSTEM},
|
| 558 |
+
{"role": "user", "content": f"Create an image generation prompt for this paper:\n\n{analysis_summary}"},
|
| 559 |
+
]
|
| 560 |
+
|
| 561 |
+
print(" π¨ Generating image prompt via Qwen...")
|
| 562 |
+
image_prompt = call_with_retry(prompt_messages, max_tokens=300, temperature=0.7)
|
| 563 |
+
if not image_prompt:
|
| 564 |
+
raise RuntimeError("Qwen returned empty image prompt")
|
| 565 |
+
|
| 566 |
+
# Add preamble for FLUX to ensure academic quality
|
| 567 |
+
full_prompt = (
|
| 568 |
+
"A detailed, clean scientific illustration for an academic paper. "
|
| 569 |
+
"Style: professional educational diagram, labeled components, "
|
| 570 |
+
"modern flat vector design, white background, high contrast, "
|
| 571 |
+
"color-coded sections, no text. "
|
| 572 |
+
f"{image_prompt.strip()}"
|
| 573 |
+
)
|
| 574 |
+
print(f" π FLUX prompt ({len(full_prompt)} chars): {full_prompt[:100]}...")
|
| 575 |
+
|
| 576 |
+
# ββ Step 2: FLUX.1-schnell β Image ββ
|
| 577 |
+
print(" πΌοΈ Calling FLUX.1-schnell...")
|
| 578 |
+
headers = {
|
| 579 |
+
"Authorization": f"Bearer {FLUX_API_KEY}",
|
| 580 |
+
"Content-Type": "application/json",
|
| 581 |
+
"Accept": "application/json",
|
| 582 |
+
}
|
| 583 |
+
payload = {
|
| 584 |
+
"prompt": full_prompt,
|
| 585 |
+
"height": 1024,
|
| 586 |
+
"width": 1024,
|
| 587 |
+
"num_inference_steps": 4,
|
| 588 |
+
"guidance_scale": 0.0,
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
response = requests.post(FLUX_API_URL, headers=headers, json=payload, timeout=60)
|
| 592 |
+
|
| 593 |
+
if response.status_code != 200:
|
| 594 |
+
raise RuntimeError(f"FLUX API error {response.status_code}: {response.text[:200]}")
|
| 595 |
+
|
| 596 |
+
result = response.json()
|
| 597 |
+
# FLUX returns {"image": "base64..."} or {"artifacts": [{"base64": "..."}]}
|
| 598 |
+
image_b64 = None
|
| 599 |
+
if "image" in result:
|
| 600 |
+
image_b64 = result["image"]
|
| 601 |
+
elif "artifacts" in result and len(result["artifacts"]) > 0:
|
| 602 |
+
image_b64 = result["artifacts"][0].get("base64", "")
|
| 603 |
+
|
| 604 |
+
if not image_b64:
|
| 605 |
+
raise RuntimeError("FLUX returned no image data")
|
| 606 |
+
|
| 607 |
+
print(f" β
Image generated ({len(image_b64)} chars base64)")
|
| 608 |
+
return image_b64
|