generate_schematic.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #!/usr/bin/env python3
  2. """
  3. Scientific schematic generation using Nano Banana 2.
  4. Generate any scientific diagram by describing it in natural language.
  5. Nano Banana 2 handles everything automatically with smart iterative refinement.
  6. Smart iteration: Only regenerates if quality is below threshold for your document type.
  7. Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.
  8. Usage:
  9. # Generate for journal paper (highest quality threshold)
  10. python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal
  11. # Generate for presentation (lower threshold, faster)
  12. python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation
  13. # Generate for poster
  14. python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster
  15. """
  16. import argparse
  17. import os
  18. import subprocess
  19. import sys
  20. from pathlib import Path
  21. def main():
  22. """Command-line interface."""
  23. parser = argparse.ArgumentParser(
  24. description="Generate scientific schematics using AI with smart iterative refinement",
  25. formatter_class=argparse.RawDescriptionHelpFormatter,
  26. epilog="""
  27. How it works:
  28. Simply describe your diagram in natural language
  29. Nano Banana 2 generates it automatically with:
  30. - Smart iteration (only regenerates if quality is below threshold)
  31. - Quality review by Gemini 3.1 Pro Preview
  32. - Document-type aware quality thresholds
  33. - Publication-ready output
  34. Document Types (quality thresholds):
  35. journal 8.5/10 - Nature, Science, peer-reviewed journals
  36. conference 8.0/10 - Conference papers
  37. thesis 8.0/10 - Dissertations, theses
  38. grant 8.0/10 - Grant proposals
  39. preprint 7.5/10 - arXiv, bioRxiv, etc.
  40. report 7.5/10 - Technical reports
  41. poster 7.0/10 - Academic posters
  42. presentation 6.5/10 - Slides, talks
  43. default 7.5/10 - General purpose
  44. Examples:
  45. # Generate for journal paper (strict quality)
  46. python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal
  47. # Generate for poster (moderate quality)
  48. python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster
  49. # Generate for slides (faster, lower threshold)
  50. python generate_schematic.py "System diagram" -o system.png --doc-type presentation
  51. # Custom max iterations
  52. python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2
  53. # Verbose output
  54. python generate_schematic.py "Circuit diagram" -o circuit.png -v
  55. Environment Variables:
  56. OPENROUTER_API_KEY Required for AI generation
  57. """
  58. )
  59. parser.add_argument("prompt",
  60. help="Description of the diagram to generate")
  61. parser.add_argument("-o", "--output", required=True,
  62. help="Output file path")
  63. parser.add_argument("--doc-type", default="default",
  64. choices=["journal", "conference", "poster", "presentation",
  65. "report", "grant", "thesis", "preprint", "default"],
  66. help="Document type for quality threshold (default: default)")
  67. parser.add_argument("--iterations", type=int, default=2,
  68. help="Maximum refinement iterations (default: 2, max: 2)")
  69. parser.add_argument("--api-key",
  70. help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")
  71. parser.add_argument("-v", "--verbose", action="store_true",
  72. help="Verbose output")
  73. args = parser.parse_args()
  74. # Check for API key
  75. api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")
  76. if not api_key:
  77. print("Error: OPENROUTER_API_KEY environment variable not set")
  78. print("\nFor AI generation, you need an OpenRouter API key.")
  79. print("Get one at: https://openrouter.ai/keys")
  80. print("\nSet it with:")
  81. print(" export OPENROUTER_API_KEY='your_api_key'")
  82. print("\nOr use --api-key flag")
  83. sys.exit(1)
  84. # Find AI generation script
  85. script_dir = Path(__file__).parent
  86. ai_script = script_dir / "generate_schematic_ai.py"
  87. if not ai_script.exists():
  88. print(f"Error: AI generation script not found: {ai_script}")
  89. sys.exit(1)
  90. # Build command
  91. cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]
  92. if args.doc_type != "default":
  93. cmd.extend(["--doc-type", args.doc_type])
  94. # Enforce max 2 iterations
  95. iterations = min(args.iterations, 2)
  96. if iterations != 2:
  97. cmd.extend(["--iterations", str(iterations)])
  98. if args.verbose:
  99. cmd.append("-v")
  100. # Execute — pass API key via environment to avoid exposure in process listings
  101. try:
  102. env = os.environ.copy()
  103. if api_key:
  104. env["OPENROUTER_API_KEY"] = api_key
  105. result = subprocess.run(cmd, check=False, env=env)
  106. sys.exit(result.returncode)
  107. except Exception as e:
  108. print(f"Error executing AI generation: {e}")
  109. sys.exit(1)
  110. if __name__ == "__main__":
  111. main()