Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
fix: update references in SKILL.md files for consistency and clarity
Timothy Kassis2b97bcadaf42
diff --git a/pyproject.toml b/pyproject.tomlindex 165cb45e..f96ea27d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "scientific-agent-skills"-version = "2.35.0"+version = "2.36.0"description = "A set of ready to use Agent Skills for research, science, engineering, analysis, finance and writing."readme = "README.md"requires-python = ">=3.13"diff --git a/scientific-skills/citation-management/scripts/generate_schematic.py b/scientific-skills/citation-management/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/citation-management/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/citation-management/scripts/generate_schematic_ai.py b/scientific-skills/citation-management/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/citation-management/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/clinical-decision-support/SKILL.md b/scientific-skills/clinical-decision-support/SKILL.mdindex 5af05f15..515f3657 100644--- a/scientific-skills/clinical-decision-support/SKILL.md+++ b/scientific-skills/clinical-decision-support/SKILL.md@@ -484,7 +484,6 @@ See the `assets/` directory for LaTeX templates:- `treatment_recommendation_template.tex` - Evidence-based clinical practice guidelines with GRADE grading- `clinical_pathway_template.tex` - TikZ decision algorithm flowcharts for treatment sequencing- `biomarker_report_template.tex` - Molecular subtype classification and genomic profile reports-- `evidence_synthesis_template.tex` - Systematic evidence review and meta-analysis summaries**Template Features:**- 0.5in margins for compact presentationdiff --git a/scientific-skills/clinical-decision-support/scripts/generate_schematic.py b/scientific-skills/clinical-decision-support/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/clinical-decision-support/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/clinical-decision-support/scripts/generate_schematic_ai.py b/scientific-skills/clinical-decision-support/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/clinical-decision-support/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/clinical-reports/scripts/generate_schematic.py b/scientific-skills/clinical-reports/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/clinical-reports/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/clinical-reports/scripts/generate_schematic_ai.py b/scientific-skills/clinical-reports/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/clinical-reports/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/hypogenic/SKILL.md b/scientific-skills/hypogenic/SKILL.mdindex 6a4da2ac..68347f5c 100644--- a/scientific-skills/hypogenic/SKILL.md+++ b/scientific-skills/hypogenic/SKILL.md@@ -227,7 +227,9 @@ Refer to `references/config_template.yaml` for a complete example configuration.## Literature Processing (HypoRefine/Union Methods)-To use literature-based hypothesis generation, you must preprocess PDF papers:+To use literature-based hypothesis generation, you must preprocess PDF papers.++> **Note:** The commands below run inside the cloned [HypoGenic repository](https://github.com/ChicagoHAI/hypothesis-generation), not from this skill directory.**Step 1: Setup GROBID** (first time only)```bash@@ -436,7 +438,7 @@ Research using hypogenic has demonstrated:**Solution:** Implement custom `extract_label()` function for domain-specific output parsing**Issue:** GROBID PDF processing fails-**Solution:** Ensure GROBID service is running (`bash ./modules/run_grobid.sh`) and PDFs are valid research papers+**Solution:** Ensure GROBID service is running (`bash ./modules/run_grobid.sh` from the cloned repo) and PDFs are valid research papers## Creating Custom Tasksdiff --git a/scientific-skills/hypothesis-generation/scripts/generate_schematic.py b/scientific-skills/hypothesis-generation/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/hypothesis-generation/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/hypothesis-generation/scripts/generate_schematic_ai.py b/scientific-skills/hypothesis-generation/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/hypothesis-generation/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/latex-posters/SKILL.md b/scientific-skills/latex-posters/SKILL.mdindex 68dd2619..45297846 100644--- a/scientific-skills/latex-posters/SKILL.md+++ b/scientific-skills/latex-posters/SKILL.md@@ -664,19 +664,13 @@ Support for international and conference-specific poster dimensions:Provide ready-to-use templates for each major package. Templates available in `assets/` directory.**beamerposter Templates**:-- `beamerposter_classic.tex` - Traditional academic style-- `beamerposter_modern.tex` - Clean, minimal design-- `beamerposter_colorful.tex` - Vibrant theme with blocks+- `beamerposter_template.tex` - Customizable beamerposter template**tikzposter Templates**:-- `tikzposter_default.tex` - Standard tikzposter layout-- `tikzposter_rays.tex` - Modern design with ray theme-- `tikzposter_wave.tex` - Professional wave-style theme+- `tikzposter_template.tex` - Customizable tikzposter template**baposter Templates**:-- `baposter_portrait.tex` - Classic portrait layout-- `baposter_landscape.tex` - Landscape multi-column-- `baposter_minimal.tex` - Minimalist design+- `baposter_template.tex` - Customizable baposter template### 6. Figure and Image Integration@@ -1574,10 +1568,8 @@ tlmgr install qrcode graphics xcolor tcolorbox subcaptionHelper scripts available in `scripts/` directory:-- `compile_poster.sh`: Automated compilation with error handling-- `generate_template.py`: Interactive template generator-- `resize_images.py`: Batch image optimization for posters-- `poster_checklist.py`: Pre-submission validation tool+- `review_poster.sh`: Poster review and validation+- `generate_schematic.py`: Generate scientific diagrams and schematics## Referencesdiff --git a/scientific-skills/latex-posters/scripts/generate_schematic.py b/scientific-skills/latex-posters/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/latex-posters/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/latex-posters/scripts/generate_schematic_ai.py b/scientific-skills/latex-posters/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/latex-posters/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/literature-review/scripts/generate_schematic.py b/scientific-skills/literature-review/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/literature-review/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/literature-review/scripts/generate_schematic_ai.py b/scientific-skills/literature-review/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/literature-review/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/markitdown/scripts/generate_schematic.py b/scientific-skills/markitdown/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/markitdown/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/markitdown/scripts/generate_schematic_ai.py b/scientific-skills/markitdown/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/markitdown/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/neuropixels-analysis/SKILL.md b/scientific-skills/neuropixels-analysis/SKILL.mdindex 2e6dc216..1a3bb2ab 100644--- a/scientific-skills/neuropixels-analysis/SKILL.md+++ b/scientific-skills/neuropixels-analysis/SKILL.md@@ -270,29 +270,29 @@ cp assets/analysis_template.py my_analysis.pypython my_analysis.py```-### reference/standard_workflow.md+### references/standard_workflow.mdDetailed step-by-step workflow with explanations for each stage.-### reference/api_reference.md+### references/api_reference.mdQuick function reference organized by module.-### reference/plotting_guide.md+### references/plotting_guide.mdComprehensive visualization guide for publication-quality figures.## Detailed Reference Guides| Topic | Reference ||-------|-----------|-| Full workflow | [references/standard_workflow.md](reference/standard_workflow.md) |-| API reference | [references/api_reference.md](reference/api_reference.md) |-| Plotting guide | [references/plotting_guide.md](reference/plotting_guide.md) |-| Preprocessing | [references/PREPROCESSING.md](reference/PREPROCESSING.md) |-| Spike sorting | [references/SPIKE_SORTING.md](reference/SPIKE_SORTING.md) |-| Motion correction | [references/MOTION_CORRECTION.md](reference/MOTION_CORRECTION.md) |-| Quality metrics | [references/QUALITY_METRICS.md](reference/QUALITY_METRICS.md) |-| Automated curation | [references/AUTOMATED_CURATION.md](reference/AUTOMATED_CURATION.md) |-| AI-assisted curation | [references/AI_CURATION.md](reference/AI_CURATION.md) |-| Waveform analysis | [references/ANALYSIS.md](reference/ANALYSIS.md) |+| Full workflow | [references/standard_workflow.md](references/standard_workflow.md) |+| API reference | [references/api_reference.md](references/api_reference.md) |+| Plotting guide | [references/plotting_guide.md](references/plotting_guide.md) |+| Preprocessing | [references/PREPROCESSING.md](references/PREPROCESSING.md) |+| Spike sorting | [references/SPIKE_SORTING.md](references/SPIKE_SORTING.md) |+| Motion correction | [references/MOTION_CORRECTION.md](references/MOTION_CORRECTION.md) |+| Quality metrics | [references/QUALITY_METRICS.md](references/QUALITY_METRICS.md) |+| Automated curation | [references/AUTOMATED_CURATION.md](references/AUTOMATED_CURATION.md) |+| AI-assisted curation | [references/AI_CURATION.md](references/AI_CURATION.md) |+| Waveform analysis | [references/ANALYSIS.md](references/ANALYSIS.md) |## Installationdiff --git a/scientific-skills/parallel-web/SKILL.md b/scientific-skills/parallel-web/SKILL.mdindex 8b911dbb..2a2e65b4 100644--- a/scientific-skills/parallel-web/SKILL.md+++ b/scientific-skills/parallel-web/SKILL.md@@ -256,7 +256,7 @@ ls sources/ # Check existing saved results| Web search (any) | `parallel_web.py search` | `python scripts/parallel_web.py search "query" -o sources/search_<topic>.md` || Deep research | `parallel_web.py research` | `python scripts/parallel_web.py research "query" -o sources/research_<topic>.md` || Citation verification | `parallel_web.py extract` | `python scripts/parallel_web.py extract "url" -o sources/extract_<source>.md` |-| Academic paper search | `research_lookup.py` | Routes to Perplexity sonar-pro-search |+| Academic paper search | `parallel_web.py search` | `python scripts/parallel_web.py search "academic query" -o sources/papers_<topic>.md` || DOI/metadata lookup | `parallel_web.py extract` | Extract from DOI URLs (verification) |### When Writing Scientific Documentsdiff --git a/scientific-skills/pdf/SKILL.md b/scientific-skills/pdf/SKILL.mdindex d3e046a5..8095f2e2 100644--- a/scientific-skills/pdf/SKILL.md+++ b/scientific-skills/pdf/SKILL.md@@ -8,7 +8,7 @@ license: Proprietary. LICENSE.txt has complete terms## Overview-This guide covers essential PDF processing operations using Python libraries and command-line tools. For advanced features, JavaScript libraries, and detailed examples, see REFERENCE.md. If you need to fill out a PDF form, read FORMS.md and follow its instructions.+This guide covers essential PDF processing operations using Python libraries and command-line tools. For advanced features, JavaScript libraries, and detailed examples, see reference.md. If you need to fill out a PDF form, read forms.md and follow its instructions.## Quick Start@@ -304,11 +304,11 @@ with open("encrypted.pdf", "wb") as output:| Create PDFs | reportlab | Canvas or Platypus || Command line merge | qpdf | `qpdf --empty --pages ...` || OCR scanned PDFs | pytesseract | Convert to image first |-| Fill PDF forms | pdf-lib or pypdf (see FORMS.md) | See FORMS.md |+| Fill PDF forms | pdf-lib or pypdf (see forms.md) | See forms.md |## Next Steps-- For advanced pypdfium2 usage, see REFERENCE.md-- For JavaScript libraries (pdf-lib), see REFERENCE.md-- If you need to fill out a PDF form, follow the instructions in FORMS.md-- For troubleshooting guides, see REFERENCE.md+- For advanced pypdfium2 usage, see reference.md+- For JavaScript libraries (pdf-lib), see reference.md+- If you need to fill out a PDF form, follow the instructions in forms.md+- For troubleshooting guides, see reference.mddiff --git a/scientific-skills/peer-review/scripts/generate_schematic.py b/scientific-skills/peer-review/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/peer-review/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/peer-review/scripts/generate_schematic_ai.py b/scientific-skills/peer-review/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/peer-review/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/pptx-posters/scripts/generate_schematic.py b/scientific-skills/pptx-posters/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/pptx-posters/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/pptx-posters/scripts/generate_schematic_ai.py b/scientific-skills/pptx-posters/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/pptx-posters/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/research-grants/SKILL.md b/scientific-skills/research-grants/SKILL.mdindex 6e413230..6d8c56f2 100644--- a/scientific-skills/research-grants/SKILL.md+++ b/scientific-skills/research-grants/SKILL.md@@ -360,7 +360,6 @@ Detailed description of how the research will be conducted.- Address regulatory approvals (IRB, IND, IDE)- Describe clinical trial design and monitoring-For detailed methodology guidance by discipline, refer to `references/research_methods.md`.### 7. Preliminary Data and Feasibility@@ -434,7 +433,6 @@ Demonstrate that the project is well-planned and achievable within the proposed- Phase-based structure with exit criteria- Demonstration and transition planning-For detailed guidance, refer to `references/timeline_planning.md`.### 9. Team Qualifications and Collaboration@@ -470,7 +468,6 @@ Demonstrate that the team has the expertise, experience, and resources to succee- Includes resource sharing or access agreements- Signed and on letterhead-For detailed guidance, refer to `references/team_building.md`.### 10. Budget and Budget Justification@@ -519,7 +516,6 @@ Develop realistic budgets that align with the proposed work and agency guideline- Explain consultant roles and rates- Show how budget aligns with timeline-For detailed budget guidance, refer to `references/budget_preparation.md`.## Review Criteria by Agency@@ -603,12 +599,11 @@ Varies by program office, but generally includes:3. **PI Capability (主持人能力)**: Track record and expertise.4. **Value (價值)**: Academic contribution and societal/industrial impact.-For detailed review criteria by agency, refer to `references/review_criteria.md` and `references/nstc_guidelines.md`.+For detailed review criteria, refer to `references/nstc_guidelines.md`.- **What if you succeed?** (Impact if the research works)- **What if you're right?** (Implications of your hypothesis)- **Who cares?** (Why it matters for national security)-For detailed review criteria by agency, refer to `references/review_criteria.md`.## Writing Principles for Competitive Proposals@@ -742,7 +737,6 @@ For detailed review criteria by agency, refer to `references/review_criteria.md`- **Young Faculty Award (YFA)**: Early career researchers, up to $500K- **Director's Fellowship**: High-risk, paradigm-shifting research-For detailed program guidance, refer to `references/funding_mechanisms.md`.## Resubmission Strategies@@ -778,7 +772,6 @@ For detailed program guidance, refer to `references/funding_mechanisms.md`.- Consider program officer feedback- May need to wait for next submission cycle-For detailed resubmission guidance, refer to `references/resubmission_strategies.md`.## Common Mistakes to Avoid@@ -926,11 +919,7 @@ This skill includes comprehensive reference files covering specific aspects of g- `references/darpa_guidelines.md`: DARPA BAAs, program offices, and proposal strategies- `references/broader_impacts.md`: Strategies for compelling broader impacts statements- `references/specific_aims_guide.md`: Writing effective specific aims pages-- `references/budget_preparation.md`: Budget development and justification-- `references/review_criteria.md`: Detailed review criteria by agency-- `references/timeline_planning.md`: Creating realistic timelines and milestones-- `references/team_building.md`: Assembling and presenting effective teams-- `references/resubmission_strategies.md`: Responding to reviews and revising proposals+- `references/nstc_guidelines.md`: NSTC-specific guidelines and review criteriaLoad these references as needed when working on specific aspects of grant writing.@@ -938,15 +927,11 @@ Load these references as needed when working on specific aspects of grant writin- `assets/nsf_project_summary_template.md`: NSF project summary structure- `assets/nih_specific_aims_template.md`: NIH specific aims page template-- `assets/timeline_gantt_template.md`: Timeline and Gantt chart examples- `assets/budget_justification_template.md`: Budget justification structure-- `assets/biosketch_templates/`: Agency-specific biosketch formats## Scripts and Tools-- `scripts/compliance_checker.py`: Verify formatting requirements-- `scripts/budget_calculator.py`: Calculate budgets with inflation and fringe-- `scripts/deadline_tracker.py`: Track submission deadlines and milestones+- `scripts/generate_schematic.py`: Generate scientific diagrams and schematics---diff --git a/scientific-skills/research-grants/scripts/generate_schematic.py b/scientific-skills/research-grants/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/research-grants/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/research-grants/scripts/generate_schematic_ai.py b/scientific-skills/research-grants/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/research-grants/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/research-lookup/scripts/generate_schematic.py b/scientific-skills/research-lookup/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/research-lookup/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/research-lookup/scripts/generate_schematic_ai.py b/scientific-skills/research-lookup/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/research-lookup/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scholar-evaluation/scripts/generate_schematic.py b/scientific-skills/scholar-evaluation/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/scholar-evaluation/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scholar-evaluation/scripts/generate_schematic_ai.py b/scientific-skills/scholar-evaluation/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/scholar-evaluation/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scientific-critical-thinking/scripts/generate_schematic.py b/scientific-skills/scientific-critical-thinking/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/scientific-critical-thinking/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scientific-critical-thinking/scripts/generate_schematic_ai.py b/scientific-skills/scientific-critical-thinking/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/scientific-critical-thinking/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scientific-schematics/SKILL.md b/scientific-skills/scientific-schematics/SKILL.mdindex 6397eb7b..def5974e 100644--- a/scientific-skills/scientific-schematics/SKILL.md+++ b/scientific-skills/scientific-schematics/SKILL.md@@ -517,7 +517,6 @@ python scripts/generate_schematic.py "diagram" -o out.png -vLoad these files for comprehensive information on specific topics:-- **`references/diagram_types.md`** - Catalog of scientific diagram types with examples- **`references/best_practices.md`** - Publication standards and accessibility guidelines### External Resourcesdiff --git a/scientific-skills/scientific-slides/SKILL.md b/scientific-skills/scientific-slides/SKILL.mdindex 2339cf2e..e2b4b20f 100644--- a/scientific-skills/scientific-slides/SKILL.md+++ b/scientific-skills/scientific-slides/SKILL.md@@ -193,7 +193,7 @@ Use the PPTX skill's html2pptx workflow to create slides that include:- Title and body text added separately- Professional layout and formatting-See `document-skills/pptx/SKILL.md` for complete PPTX creation documentation.+See `scientific-skills/pptx/SKILL.md` for complete PPTX creation documentation.---@@ -503,7 +503,7 @@ python scripts/slides_to_pdf.py slides/*.png -o presentation.pdf**Best for**: Editable slides, custom designs, template-based workflows-**Reference**: See `document-skills/pptx/SKILL.md` for complete documentation+**Reference**: See `scientific-skills/pptx/SKILL.md` for complete documentationUse Nano Banana Pro with `--visual-only` to generate images, then build PPTX with text.@@ -567,7 +567,7 @@ Implement iterative improvement through visual inspection. For complete workflowpython scripts/pdf_to_images.py presentation.pdf review/slide --dpi 150# Or use pptx skill's thumbnail tool-python ../document-skills/pptx/scripts/thumbnail.py presentation.pptx review/thumb+python scientific-skills/pptx/scripts/thumbnail.py presentation.pptx review/thumb```**Step 3: Systematic Inspection**@@ -722,7 +722,7 @@ and discussion (slides 13-14) BEFORE creating slides.**Option A: PowerPoint (via PPTX skill)**1. Read `assets/powerpoint_design_guide.md`-2. Read `document-skills/pptx/SKILL.md`+2. Read `scientific-skills/pptx/SKILL.md`3. Choose approach (programmatic or template-based)4. Create master slides with consistent design5. Build presentation following outline@@ -795,7 +795,7 @@ and discussion (slides 13-14) BEFORE creating slides.python scripts/pdf_to_images.py presentation.pdf review/slides# Or create thumbnail grid-python ../document-skills/pptx/scripts/thumbnail.py presentation.pptx review/grid+python scientific-skills/pptx/scripts/thumbnail.py presentation.pptx review/grid```**Systematic Review**:@@ -1034,7 +1034,7 @@ python scripts/pdf_to_images.py presentation.pdf output/slide --dpi 150### PPTX Skill Scripts-From `document-skills/pptx/scripts/`:+From `scientific-skills/pptx/scripts/`:- `thumbnail.py`: Create thumbnail grids- `rearrange.py`: Duplicate and reorder slides- `inventory.py`: Extract text content@@ -1132,7 +1132,7 @@ If you need editable slides (e.g., for company templates):3. **Build PPTX** using the PPTX skill with generated images4. **Add text** separately using PPTX workflow-See `document-skills/pptx/SKILL.md` for complete PowerPoint workflow.+See `scientific-skills/pptx/SKILL.md` for complete PowerPoint workflow.## Summary: Key Principlesdiff --git a/scientific-skills/scientific-slides/scripts/generate_schematic.py b/scientific-skills/scientific-slides/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/scientific-slides/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scientific-slides/scripts/generate_schematic_ai.py b/scientific-skills/scientific-slides/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/scientific-slides/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scientific-visualization/SKILL.md b/scientific-skills/scientific-visualization/SKILL.mdindex e0d4ddda..a0ab316a 100644--- a/scientific-skills/scientific-visualization/SKILL.md+++ b/scientific-skills/scientific-visualization/SKILL.md@@ -640,10 +640,10 @@ sns.set_context('paper', font_scale=1.2) # Increase if needed#### Additional ResourcesFor more detailed seaborn information, see:-- `scientific-packages/seaborn/SKILL.md` - Comprehensive seaborn documentation-- `scientific-packages/seaborn/references/examples.md` - Practical use cases-- `scientific-packages/seaborn/references/function_reference.md` - Complete API reference-- `scientific-packages/seaborn/references/objects_interface.md` - Modern declarative API+- `scientific-skills/seaborn/SKILL.md` - Comprehensive seaborn documentation+- `scientific-skills/seaborn/references/examples.md` - Practical use cases+- `scientific-skills/seaborn/references/function_reference.md` - Complete API reference+- `scientific-skills/seaborn/references/objects_interface.md` - Modern declarative API### Plotly- Interactive figures for explorationdiff --git a/scientific-skills/scientific-writing/SKILL.md b/scientific-skills/scientific-writing/SKILL.mdindex 1b8c8ac3..b65a5415 100644--- a/scientific-skills/scientific-writing/SKILL.md+++ b/scientific-skills/scientific-writing/SKILL.md@@ -681,7 +681,6 @@ The venue-templates skill provides:- `venue_writing_styles.md`: Master style comparison- Venue-specific guides: `nature_science_style.md`, `cell_press_style.md`, `medical_journal_styles.md`, `ml_conference_style.md`, `cs_conference_style.md`- `reviewer_expectations.md`: What reviewers look for at each venue-- Writing examples in `assets/examples/`**Workflow**: First use this skill for general scientific writing principles (IMRAD, clarity, citations), then consult venue-templates for venue-specific style adaptation.diff --git a/scientific-skills/scientific-writing/scripts/generate_image.py b/scientific-skills/scientific-writing/scripts/generate_image.pynew file mode 100755index 00000000..9c613b89--- /dev/null+++ b/scientific-skills/scientific-writing/scripts/generate_image.py@@ -0,0 +1,281 @@+#!/usr/bin/env python3+"""+Generate and edit images using OpenRouter API with various image generation models.++Supports models like:+- google/gemini-3.1-flash-image-preview (generation and editing)+- black-forest-labs/flux.2-pro (generation and editing)+- black-forest-labs/flux.2-flex (generation)+- And more image generation models available on OpenRouter++For image editing, provide an input image along with an editing prompt.+"""++import sys+import json+import base64+import argparse+from pathlib import Path+from typing import Optional+++def check_env_file() -> Optional[str]:+ """Check if .env file exists and contains OPENROUTER_API_KEY."""+ # Look for .env in current directory and parent directories+ current_dir = Path.cwd()+ for parent in [current_dir] + list(current_dir.parents):+ env_file = parent / ".env"+ if env_file.exists():+ with open(env_file, 'r') as f:+ for line in f:+ if line.startswith('OPENROUTER_API_KEY='):+ api_key = line.split('=', 1)[1].strip().strip('"').strip("'")+ if api_key:+ return api_key+ return None+++def load_image_as_base64(image_path: str) -> str:+ """Load an image file and return it as a base64 data URL."""+ path = Path(image_path)+ if not path.exists():+ print(f"❌ Error: Image file not found: {image_path}")+ sys.exit(1)++ # Determine MIME type from extension+ ext = path.suffix.lower()+ mime_types = {+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ }+ mime_type = mime_types.get(ext, 'image/png')++ with open(path, 'rb') as f:+ image_data = f.read()++ base64_data = base64.b64encode(image_data).decode('utf-8')+ return f"data:{mime_type};base64,{base64_data}"+++def save_base64_image(base64_data: str, output_path: str) -> None:+ """Save base64 encoded image to file."""+ # Remove data URL prefix if present+ if ',' in base64_data:+ base64_data = base64_data.split(',', 1)[1]++ # Decode and save+ image_data = base64.b64decode(base64_data)+ with open(output_path, 'wb') as f:+ f.write(image_data)+++def generate_image(+ prompt: str,+ model: str = "google/gemini-3.1-flash-image-preview",+ output_path: str = "generated_image.png",+ api_key: Optional[str] = None,+ input_image: Optional[str] = None+) -> dict:+ """+ Generate or edit an image using OpenRouter API.++ Args:+ prompt: Text description of the image to generate, or editing instructions+ model: OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)+ output_path: Path to save the generated image+ api_key: OpenRouter API key (will check .env if not provided)+ input_image: Path to an input image for editing (optional)++ Returns:+ dict: Response from OpenRouter API+ """+ try:+ import requests+ except ImportError:+ print("Error: 'requests' library not found. Install with: pip install requests")+ sys.exit(1)++ # Check for API key+ if not api_key:+ api_key = check_env_file()++ if not api_key:+ print("❌ Error: OPENROUTER_API_KEY not found!")+ print("\nPlease create a .env file in your project directory with:")+ print("OPENROUTER_API_KEY=your-api-key-here")+ print("\nOr set the environment variable:")+ print("export OPENROUTER_API_KEY=your-api-key-here")+ print("\nGet your API key from: https://openrouter.ai/keys")+ sys.exit(1)++ # Determine if this is generation or editing+ is_editing = input_image is not None++ if is_editing:+ print(f"✏️ Editing image with model: {model}")+ print(f"📷 Input image: {input_image}")+ print(f"📝 Edit prompt: {prompt}")++ # Load input image as base64+ image_data_url = load_image_as_base64(input_image)++ # Build multimodal message content for image editing+ message_content = [+ {+ "type": "text",+ "text": prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ else:+ print(f"🎨 Generating image with model: {model}")+ print(f"📝 Prompt: {prompt}")+ message_content = prompt++ # Make API request+ response = requests.post(+ url="https://openrouter.ai/api/v1/chat/completions",+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ },+ json={+ "model": model,+ "messages": [+ {+ "role": "user",+ "content": message_content+ }+ ],+ "modalities": ["image", "text"]+ }+ )++ # Check for errors+ if response.status_code != 200:+ print(f"❌ API Error ({response.status_code}): {response.text}")+ sys.exit(1)++ result = response.json()++ # Extract and save image+ if result.get("choices"):+ message = result["choices"][0]["message"]++ # Handle both 'images' and 'content' response formats+ images = []++ if message.get("images"):+ images = message["images"]+ elif message.get("content"):+ # Some models return content as array with image parts+ content = message["content"]+ if isinstance(content, list):+ for part in content:+ if isinstance(part, dict) and part.get("type") == "image":+ images.append(part)++ if images:+ # Save the first image+ image = images[0]+ if "image_url" in image:+ image_url = image["image_url"]["url"]+ save_base64_image(image_url, output_path)+ print(f"✅ Image saved to: {output_path}")+ elif "url" in image:+ save_base64_image(image["url"], output_path)+ print(f"✅ Image saved to: {output_path}")+ else:+ print(f"⚠️ Unexpected image format: {image}")+ else:+ print("⚠️ No image found in response")+ if message.get("content"):+ print(f"Response content: {message['content']}")+ else:+ print("❌ No choices in response")+ print(f"Response: {json.dumps(result, indent=2)}")++ return result+++def main():+ parser = argparse.ArgumentParser(+ description="Generate or edit images using OpenRouter API",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate with default model (Gemini 3.1 Flash Image Preview)+ python generate_image.py "A beautiful sunset over mountains"++ # Use a specific model+ python generate_image.py "A cat in space" --model "black-forest-labs/flux.2-pro"++ # Specify output path+ python generate_image.py "Abstract art" --output my_image.png++ # Edit an existing image+ python generate_image.py "Make the sky purple" --input photo.jpg --output edited.png++ # Edit with a specific model+ python generate_image.py "Add a hat to the person" --input portrait.png -m "black-forest-labs/flux.2-pro"++Popular image models:+ - google/gemini-3.1-flash-image-preview (default, high quality, generation + editing)+ - black-forest-labs/flux.2-pro (fast, high quality, generation + editing)+ - black-forest-labs/flux.2-flex (development version)+ """+ )++ parser.add_argument(+ "prompt",+ type=str,+ help="Text description of the image to generate, or editing instructions"+ )++ parser.add_argument(+ "--model", "-m",+ type=str,+ default="google/gemini-3.1-flash-image-preview",+ help="OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)"+ )++ parser.add_argument(+ "--output", "-o",+ type=str,+ default="generated_image.png",+ help="Output file path (default: generated_image.png)"+ )++ parser.add_argument(+ "--input", "-i",+ type=str,+ help="Input image path for editing (enables edit mode)"+ )++ parser.add_argument(+ "--api-key",+ type=str,+ help="OpenRouter API key (will check .env if not provided)"+ )++ args = parser.parse_args()++ generate_image(+ prompt=args.prompt,+ model=args.model,+ output_path=args.output,+ api_key=args.api_key,+ input_image=args.input+ )+++if __name__ == "__main__":+ main()diff --git a/scientific-skills/scientific-writing/scripts/generate_schematic.py b/scientific-skills/scientific-writing/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/scientific-writing/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/scientific-writing/scripts/generate_schematic_ai.py b/scientific-skills/scientific-writing/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/scientific-writing/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/treatment-plans/scripts/generate_schematic.py b/scientific-skills/treatment-plans/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/treatment-plans/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/treatment-plans/scripts/generate_schematic_ai.py b/scientific-skills/treatment-plans/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/treatment-plans/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/venue-templates/SKILL.md b/scientific-skills/venue-templates/SKILL.mdindex a879f481..5d280706 100644--- a/scientific-skills/venue-templates/SKILL.md+++ b/scientific-skills/venue-templates/SKILL.md@@ -657,7 +657,6 @@ ISMB poster specifications:- Include: QR code for paper/supplementary materialsAvailable templates:- assets/posters/beamerposter_academic.tex-- assets/posters/tikzposter_research.tex```## Updates and Maintenancediff --git a/scientific-skills/venue-templates/scripts/generate_schematic.py b/scientific-skills/venue-templates/scripts/generate_schematic.pynew file mode 100644index 00000000..6843e0a1--- /dev/null+++ b/scientific-skills/venue-templates/scripts/generate_schematic.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""+Scientific schematic generation using Nano Banana 2.++Generate any scientific diagram by describing it in natural language.+Nano Banana 2 handles everything automatically with smart iterative refinement.++Smart iteration: Only regenerates if quality is below threshold for your document type.+Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.++Usage:+ # Generate for journal paper (highest quality threshold)+ python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal++ # Generate for presentation (lower threshold, faster)+ python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation++ # Generate for poster+ python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster+"""++import argparse+import os+import subprocess+import sys+from pathlib import Path+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+How it works:+ Simply describe your diagram in natural language+ Nano Banana 2 generates it automatically with:+ - Smart iteration (only regenerates if quality is below threshold)+ - Quality review by Gemini 3.1 Pro Preview+ - Document-type aware quality thresholds+ - Publication-ready output++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Examples:+ # Generate for journal paper (strict quality)+ python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal++ # Generate for poster (moderate quality)+ python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster++ # Generate for slides (faster, lower threshold)+ python generate_schematic.py "System diagram" -o system.png --doc-type presentation++ # Custom max iterations+ python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2++ # Verbose output+ python generate_schematic.py "Circuit diagram" -o circuit.png -v++Environment Variables:+ OPENROUTER_API_KEY Required for AI generation+ """+ )++ parser.add_argument("prompt",+ help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output file path")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--api-key",+ help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nFor AI generation, you need an OpenRouter API key.")+ print("Get one at: https://openrouter.ai/keys")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr use --api-key flag")+ sys.exit(1)++ # Find AI generation script+ script_dir = Path(__file__).parent+ ai_script = script_dir / "generate_schematic_ai.py"++ if not ai_script.exists():+ print(f"Error: AI generation script not found: {ai_script}")+ sys.exit(1)++ # Build command+ cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]++ if args.doc_type != "default":+ cmd.extend(["--doc-type", args.doc_type])++ # Enforce max 2 iterations+ iterations = min(args.iterations, 2)+ if iterations != 2:+ cmd.extend(["--iterations", str(iterations)])++ if args.verbose:+ cmd.append("-v")++ # Execute — pass API key via environment to avoid exposure in process listings+ try:+ env = os.environ.copy()+ if api_key:+ env["OPENROUTER_API_KEY"] = api_key+ result = subprocess.run(cmd, check=False, env=env)+ sys.exit(result.returncode)+ except Exception as e:+ print(f"Error executing AI generation: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+diff --git a/scientific-skills/venue-templates/scripts/generate_schematic_ai.py b/scientific-skills/venue-templates/scripts/generate_schematic_ai.pynew file mode 100644index 00000000..52170753--- /dev/null+++ b/scientific-skills/venue-templates/scripts/generate_schematic_ai.py@@ -0,0 +1,817 @@+#!/usr/bin/env python3+"""+AI-powered scientific schematic generation using Nano Banana 2.++This script uses a smart iterative refinement approach:+1. Generate initial image with Nano Banana 2+2. AI quality review using Gemini 3.1 Pro Preview for scientific critique+3. Only regenerate if quality is below threshold for document type+4. Repeat until quality meets standards (max iterations)++Requirements:+ - OPENROUTER_API_KEY environment variable+ - requests library++Usage:+ python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png+ python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2+ python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster+"""++import argparse+import base64+import json+import os+import sys+import time+from pathlib import Path+from typing import Optional, Dict, Any, List, Tuple++try:+ import requests+except ImportError:+ print("Error: requests library not found. Install with: pip install requests")+ sys.exit(1)++# Try to load .env file from multiple potential locations+def _load_env_file():+ """Load .env file from current directory or script directory only."""+ try:+ from dotenv import load_dotenv+ except ImportError:+ return False++ for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:+ if candidate.exists():+ load_dotenv(dotenv_path=candidate, override=False)+ return True++ return False+++class ScientificSchematicGenerator:+ """Generate scientific schematics using AI with smart iterative refinement.++ Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.+ Multiple passes only occur if the generated schematic doesn't meet the+ quality threshold for the target document type.+ """++ # Quality thresholds by document type (score out of 10)+ # Higher thresholds for more formal publications+ QUALITY_THRESHOLDS = {+ "journal": 8.5, # Nature, Science, etc. - highest standards+ "conference": 8.0, # Conference papers - high standards+ "poster": 7.0, # Academic posters - good quality+ "presentation": 6.5, # Slides/talks - clear but less formal+ "report": 7.5, # Technical reports - professional+ "grant": 8.0, # Grant proposals - must be compelling+ "thesis": 8.0, # Dissertations - formal academic+ "preprint": 7.5, # arXiv, etc. - good quality+ "default": 7.5, # Default threshold+ }++ # Scientific diagram best practices prompt template+ SCIENTIFIC_DIAGRAM_GUIDELINES = """+Create a high-quality scientific diagram with these requirements:++VISUAL QUALITY:+- Clean white or light background (no textures or gradients)+- High contrast for readability and printing+- Professional, publication-ready appearance+- Sharp, clear lines and text+- Adequate spacing between elements to prevent crowding++TYPOGRAPHY:+- Clear, readable sans-serif fonts (Arial, Helvetica style)+- Minimum 10pt font size for all labels+- Consistent font sizes throughout+- All text horizontal or clearly readable+- No overlapping text++SCIENTIFIC STANDARDS:+- Accurate representation of concepts+- Clear labels for all components+- Include scale bars, legends, or axes where appropriate+- Use standard scientific notation and symbols+- Include units where applicable++ACCESSIBILITY:+- Colorblind-friendly color palette (use Okabe-Ito colors if using color)+- High contrast between elements+- Redundant encoding (shapes + colors, not just colors)+- Works well in grayscale++LAYOUT:+- Logical flow (left-to-right or top-to-bottom)+- Clear visual hierarchy+- Balanced composition+- Appropriate use of whitespace+- No clutter or unnecessary decorative elements++IMPORTANT - NO FIGURE NUMBERS:+- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image+- Do NOT add captions or titles like "Figure: ..." at the top or bottom+- Figure numbers and captions are added separately in the document/LaTeX+- The diagram should contain only the visual content itself+"""++ def __init__(self, api_key: Optional[str] = None, verbose: bool = False):+ """+ Initialize the generator.++ Args:+ api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)+ verbose: Print detailed progress information+ """+ # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")++ # If not found in environment, try loading from .env file+ if not self.api_key:+ _load_env_file()+ self.api_key = os.getenv("OPENROUTER_API_KEY")++ if not self.api_key:+ raise ValueError(+ "OPENROUTER_API_KEY not found. Please either:\n"+ " 1. Set the OPENROUTER_API_KEY environment variable\n"+ " 2. Add OPENROUTER_API_KEY to your .env file\n"+ " 3. Pass api_key parameter to the constructor\n"+ "Get your API key from: https://openrouter.ai/keys"+ )++ self.verbose = verbose+ self._last_error = None # Track last error for better reporting+ self.base_url = "https://openrouter.ai/api/v1"+ # Nano Banana 2 - Google's advanced image generation model+ # https://openrouter.ai/google/gemini-3-pro-image-preview+ self.image_model = "google/gemini-3.1-flash-image-preview"+ # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning+ self.review_model = "google/gemini-3.1-pro-preview"++ def _log(self, message: str):+ """Log message if verbose mode is enabled."""+ if self.verbose:+ print(f"[{time.strftime('%H:%M:%S')}] {message}")++ def _make_request(self, model: str, messages: List[Dict[str, Any]],+ modalities: Optional[List[str]] = None) -> Dict[str, Any]:+ """+ Make a request to OpenRouter API.++ Args:+ model: Model identifier+ messages: List of message dictionaries+ modalities: Optional list of modalities (e.g., ["image", "text"])++ Returns:+ API response as dictionary+ """+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/scientific-writer",+ "X-Title": "Scientific Schematic Generator"+ }++ payload = {+ "model": model,+ "messages": messages+ }++ if modalities:+ payload["modalities"] = modalities++ self._log(f"Making request to {model}...")++ try:+ response = requests.post(+ f"{self.base_url}/chat/completions",+ headers=headers,+ json=payload,+ timeout=120+ )++ # Try to get response body even on error+ try:+ response_json = response.json()+ except json.JSONDecodeError:+ response_json = {"raw_text": response.text[:500]}++ # Check for HTTP errors but include response body in error message+ if response.status_code != 200:+ error_detail = response_json.get("error", response_json)+ self._log(f"HTTP {response.status_code}: {error_detail}")+ raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")++ return response_json+ except requests.exceptions.Timeout:+ raise RuntimeError("API request timed out after 120 seconds")+ except requests.exceptions.RequestException as e:+ raise RuntimeError(f"API request failed: {str(e)}")++ def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:+ """+ Extract base64-encoded image from API response.++ For Nano Banana 2, images are returned in the 'images' field of the message,+ not in the 'content' field.++ Args:+ response: API response dictionary++ Returns:+ Image bytes or None if not found+ """+ try:+ choices = response.get("choices", [])+ if not choices:+ self._log("No choices in response")+ return None++ message = choices[0].get("message", {})++ # IMPORTANT: Nano Banana 2 returns images in the 'images' field+ images = message.get("images", [])+ if images and len(images) > 0:+ self._log(f"Found {len(images)} image(s) in 'images' field")++ # Get first image+ first_image = images[0]+ if isinstance(first_image, dict):+ # Extract image_url+ if first_image.get("type") == "image_url":+ url = first_image.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")++ if url and url.startswith("data:image"):+ # Extract base64 data after comma+ if "," in url:+ base64_str = url.split(",", 1)[1]+ # Clean whitespace+ base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Extracted base64 data (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Fallback: check content field (for other models or future changes)+ content = message.get("content", "")++ if self.verbose:+ self._log(f"Content type: {type(content)}, length: {len(str(content))}")++ # Handle string content+ if isinstance(content, str) and "data:image" in content:+ import re+ match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)+ if match:+ base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content field (length: {len(base64_str)})")+ return base64.b64decode(base64_str)++ # Handle list content+ if isinstance(content, list):+ for i, block in enumerate(content):+ if isinstance(block, dict) and block.get("type") == "image_url":+ url = block.get("image_url", {})+ if isinstance(url, dict):+ url = url.get("url", "")+ if url and url.startswith("data:image") and "," in url:+ base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')+ self._log(f"Found image in content block {i}")+ return base64.b64decode(base64_str)++ self._log("No image data found in response")+ return None++ except Exception as e:+ self._log(f"Error extracting image: {str(e)}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def _image_to_base64(self, image_path: str) -> str:+ """+ Convert image file to base64 data URL.++ Args:+ image_path: Path to image file++ Returns:+ Base64 data URL string+ """+ with open(image_path, "rb") as f:+ image_data = f.read()++ # Determine image type from extension+ ext = Path(image_path).suffix.lower()+ mime_type = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp"+ }.get(ext, "image/png")++ base64_data = base64.b64encode(image_data).decode("utf-8")+ return f"data:{mime_type};base64,{base64_data}"++ def generate_image(self, prompt: str) -> Optional[bytes]:+ """+ Generate an image using Nano Banana 2.++ Args:+ prompt: Description of the diagram to generate++ Returns:+ Image bytes or None if generation failed+ """+ self._last_error = None # Reset error++ messages = [+ {+ "role": "user",+ "content": prompt+ }+ ]++ try:+ response = self._make_request(+ model=self.image_model,+ messages=messages,+ modalities=["image", "text"]+ )++ # Debug: print response structure if verbose+ if self.verbose:+ self._log(f"Response keys: {response.keys()}")+ if "error" in response:+ self._log(f"API Error: {response['error']}")+ if "choices" in response and response["choices"]:+ msg = response["choices"][0].get("message", {})+ self._log(f"Message keys: {msg.keys()}")+ # Show content preview without printing huge base64 data+ content = msg.get("content", "")+ if isinstance(content, str):+ preview = content[:200] + "..." if len(content) > 200 else content+ self._log(f"Content preview: {preview}")+ elif isinstance(content, list):+ self._log(f"Content is list with {len(content)} items")+ for i, item in enumerate(content[:3]):+ if isinstance(item, dict):+ self._log(f" Item {i}: type={item.get('type')}")++ # Check for API errors in response+ if "error" in response:+ error_msg = response["error"]+ if isinstance(error_msg, dict):+ error_msg = error_msg.get("message", str(error_msg))+ self._last_error = f"API Error: {error_msg}"+ print(f"✗ {self._last_error}")+ return None++ image_data = self._extract_image_from_response(response)+ if image_data:+ self._log(f"✓ Generated image ({len(image_data)} bytes)")+ else:+ self._last_error = "No image data in API response - model may not support image generation"+ self._log(f"✗ {self._last_error}")+ # Additional debug info when image extraction fails+ if self.verbose and "choices" in response:+ msg = response["choices"][0].get("message", {})+ self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")++ return image_data+ except RuntimeError as e:+ self._last_error = str(e)+ self._log(f"✗ Generation failed: {self._last_error}")+ return None+ except Exception as e:+ self._last_error = f"Unexpected error: {str(e)}"+ self._log(f"✗ Generation failed: {self._last_error}")+ import traceback+ if self.verbose:+ traceback.print_exc()+ return None++ def review_image(self, image_path: str, original_prompt: str,+ iteration: int, doc_type: str = "default",+ max_iterations: int = 2) -> Tuple[str, float, bool]:+ """+ Review generated image using Gemini 3.1 Pro Preview for quality analysis.++ Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to+ evaluate the schematic quality and determine if regeneration is needed.++ Args:+ image_path: Path to the generated image+ original_prompt: Original user prompt+ iteration: Current iteration number+ doc_type: Document type (journal, poster, presentation, etc.)+ max_iterations: Maximum iterations allowed++ Returns:+ Tuple of (critique text, quality score 0-10, needs_improvement bool)+ """+ # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis+ image_data_url = self._image_to_base64(image_path)++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.++ORIGINAL REQUEST: {original_prompt}++DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)+ITERATION: {iteration}/{max_iterations}++Carefully evaluate this diagram on these criteria:++1. **Scientific Accuracy** (0-2 points)+ - Correct representation of concepts+ - Proper notation and symbols+ - Accurate relationships shown++2. **Clarity and Readability** (0-2 points)+ - Easy to understand at a glance+ - Clear visual hierarchy+ - No ambiguous elements++3. **Label Quality** (0-2 points)+ - All important elements labeled+ - Labels are readable (appropriate font size)+ - Consistent labeling style++4. **Layout and Composition** (0-2 points)+ - Logical flow (top-to-bottom or left-to-right)+ - Balanced use of space+ - No overlapping elements++5. **Professional Appearance** (0-2 points)+ - Publication-ready quality+ - Clean, crisp lines and shapes+ - Appropriate colors/contrast++RESPOND IN THIS EXACT FORMAT:+SCORE: [total score 0-10]++STRENGTHS:+- [strength 1]+- [strength 2]++ISSUES:+- [issue 1 if any]+- [issue 2 if any]++VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]++If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.+If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": review_prompt+ },+ {+ "type": "image_url",+ "image_url": {+ "url": image_data_url+ }+ }+ ]+ }+ ]++ try:+ # Use Gemini 3.1 Pro Preview for high-quality review+ response = self._make_request(+ model=self.review_model,+ messages=messages+ )++ # Extract text response+ choices = response.get("choices", [])+ if not choices:+ return "Image generated successfully", 8.0++ message = choices[0].get("message", {})+ content = message.get("content", "")++ # Check reasoning field (Nano Banana 2 puts analysis here)+ reasoning = message.get("reasoning", "")+ if reasoning and not content:+ content = reasoning++ if isinstance(content, list):+ # Extract text from content blocks+ text_parts = []+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ content = "\n".join(text_parts)++ # Try to extract score+ score = 7.5 # Default score if extraction fails+ import re++ # Look for SCORE: X or SCORE: X/10 format+ score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))+ else:+ # Fallback: look for any score pattern+ score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)+ if score_match:+ score = float(score_match.group(1))++ # Determine if improvement is needed based on verdict or score+ needs_improvement = False+ if "NEEDS_IMPROVEMENT" in content.upper():+ needs_improvement = True+ elif score < threshold:+ needs_improvement = True++ self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")+ self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")++ return (content if content else "Image generated successfully",+ score,+ needs_improvement)+ except Exception as e:+ self._log(f"Review skipped: {str(e)}")+ # Don't fail the whole process if review fails - assume acceptable+ return "Image generated successfully (review skipped)", 7.5, False++ def improve_prompt(self, original_prompt: str, critique: str,+ iteration: int) -> str:+ """+ Improve the generation prompt based on critique.++ Args:+ original_prompt: Original user prompt+ critique: Review critique from previous iteration+ iteration: Current iteration number++ Returns:+ Improved prompt for next generation+ """+ improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {original_prompt}++ITERATION {iteration}: Based on previous feedback, address these specific improvements:+{critique}++Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""++ return improved_prompt++ def generate_iterative(self, user_prompt: str, output_path: str,+ iterations: int = 2,+ doc_type: str = "default") -> Dict[str, Any]:+ """+ Generate scientific schematic with smart iterative refinement.++ Only regenerates if the quality score is below the threshold for the+ specified document type. This saves API calls and time when the first+ generation is already good enough.++ Args:+ user_prompt: User's description of desired diagram+ output_path: Path to save final image+ iterations: Maximum refinement iterations (default: 2, max: 2)+ doc_type: Document type for quality threshold (journal, poster, etc.)++ Returns:+ Dictionary with generation results and metadata+ """+ output_path = Path(output_path)+ output_dir = output_path.parent+ output_dir.mkdir(parents=True, exist_ok=True)++ base_name = output_path.stem+ extension = output_path.suffix or ".png"++ # Get quality threshold for this document type+ threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),+ self.QUALITY_THRESHOLDS["default"])++ results = {+ "user_prompt": user_prompt,+ "doc_type": doc_type,+ "quality_threshold": threshold,+ "iterations": [],+ "final_image": None,+ "final_score": 0.0,+ "success": False,+ "early_stop": False,+ "early_stop_reason": None+ }++ current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}++USER REQUEST: {user_prompt}++Generate a publication-quality scientific diagram that meets all the guidelines above."""++ print(f"\n{'='*60}")+ print(f"Generating Scientific Schematic")+ print(f"{'='*60}")+ print(f"Description: {user_prompt}")+ print(f"Document Type: {doc_type}")+ print(f"Quality Threshold: {threshold}/10")+ print(f"Max Iterations: {iterations}")+ print(f"Output: {output_path}")+ print(f"{'='*60}\n")++ for i in range(1, iterations + 1):+ print(f"\n[Iteration {i}/{iterations}]")+ print("-" * 40)++ # Generate image+ print(f"Generating image...")+ image_data = self.generate_image(current_prompt)++ if not image_data:+ error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')+ print(f"✗ Generation failed: {error_msg}")+ results["iterations"].append({+ "iteration": i,+ "success": False,+ "error": error_msg+ })+ continue++ # Save iteration image+ iter_path = output_dir / f"{base_name}_v{i}{extension}"+ with open(iter_path, "wb") as f:+ f.write(image_data)+ print(f"✓ Saved: {iter_path}")++ # Review image using Gemini 3.1 Pro Preview+ print(f"Reviewing image with Gemini 3.1 Pro Preview...")+ critique, score, needs_improvement = self.review_image(+ str(iter_path), user_prompt, i, doc_type, iterations+ )+ print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")++ # Save iteration results+ iteration_result = {+ "iteration": i,+ "image_path": str(iter_path),+ "prompt": current_prompt,+ "critique": critique,+ "score": score,+ "needs_improvement": needs_improvement,+ "success": True+ }+ results["iterations"].append(iteration_result)++ # Check if quality is acceptable - STOP EARLY if so+ if not needs_improvement:+ print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")+ print(f" No further iterations needed!")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ results["early_stop"] = True+ results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"+ break++ # If this is the last iteration, we're done regardless+ if i == iterations:+ print(f"\n⚠ Maximum iterations reached")+ results["final_image"] = str(iter_path)+ results["final_score"] = score+ results["success"] = True+ break++ # Quality below threshold - improve prompt for next iteration+ print(f"\n⚠ Quality below threshold ({score} < {threshold})")+ print(f"Improving prompt based on feedback...")+ current_prompt = self.improve_prompt(user_prompt, critique, i + 1)++ # Copy final version to output path+ if results["success"] and results["final_image"]:+ final_iter_path = Path(results["final_image"])+ if final_iter_path != output_path:+ import shutil+ shutil.copy(final_iter_path, output_path)+ print(f"\n✓ Final image: {output_path}")++ # Save review log+ log_path = output_dir / f"{base_name}_review_log.json"+ with open(log_path, "w") as f:+ json.dump(results, f, indent=2)+ print(f"✓ Review log: {log_path}")++ print(f"\n{'='*60}")+ print(f"Generation Complete!")+ print(f"Final Score: {results['final_score']}/10")+ if results["early_stop"]:+ print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")+ print(f"{'='*60}\n")++ return results+++def main():+ """Command-line interface."""+ parser = argparse.ArgumentParser(+ description="Generate scientific schematics using AI with smart iterative refinement",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Generate a flowchart for a journal paper+ python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal++ # Generate neural network architecture for presentation (lower threshold)+ python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation++ # Generate with custom max iterations for poster+ python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster++ # Verbose output+ python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v++Document Types (quality thresholds):+ journal 8.5/10 - Nature, Science, peer-reviewed journals+ conference 8.0/10 - Conference papers+ thesis 8.0/10 - Dissertations, theses+ grant 8.0/10 - Grant proposals+ preprint 7.5/10 - arXiv, bioRxiv, etc.+ report 7.5/10 - Technical reports+ poster 7.0/10 - Academic posters+ presentation 6.5/10 - Slides, talks+ default 7.5/10 - General purpose++Note: Multiple iterations only occur if quality is BELOW the threshold.+ If the first generation meets the threshold, no extra API calls are made.++Environment:+ OPENROUTER_API_KEY OpenRouter API key (required)+ """+ )++ parser.add_argument("prompt", help="Description of the diagram to generate")+ parser.add_argument("-o", "--output", required=True,+ help="Output image path (e.g., diagram.png)")+ parser.add_argument("--iterations", type=int, default=2,+ help="Maximum refinement iterations (default: 2, max: 2)")+ parser.add_argument("--doc-type", default="default",+ choices=["journal", "conference", "poster", "presentation",+ "report", "grant", "thesis", "preprint", "default"],+ help="Document type for quality threshold (default: default)")+ parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")+ parser.add_argument("-v", "--verbose", action="store_true",+ help="Verbose output")++ args = parser.parse_args()++ # Check for API key+ api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")+ if not api_key:+ print("Error: OPENROUTER_API_KEY environment variable not set")+ print("\nSet it with:")+ print(" export OPENROUTER_API_KEY='your_api_key'")+ print("\nOr provide via --api-key flag")+ sys.exit(1)++ # Validate iterations - enforce max of 2+ if args.iterations < 1 or args.iterations > 2:+ print("Error: Iterations must be between 1 and 2")+ sys.exit(1)++ try:+ generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)+ results = generator.generate_iterative(+ user_prompt=args.prompt,+ output_path=args.output,+ iterations=args.iterations,+ doc_type=args.doc_type+ )++ if results["success"]:+ print(f"\n✓ Success! Image saved to: {args.output}")+ if results.get("early_stop"):+ print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")+ sys.exit(0)+ else:+ print(f"\n✗ Generation failed. Check review log for details.")+ sys.exit(1)+ except Exception as e:+ print(f"\n✗ Error: {str(e)}")+ sys.exit(1)+++if __name__ == "__main__":+ main()+