import os import logging from pathlib import Path from typing import Dict, List import google.generativeai as genai logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class MarketAnalyzer: def __init__(self): # Initialize Gemini api_key = os.getenv("GOOGLE_API_KEY") if not api_key: raise ValueError("GOOGLE_API_KEY not found") genai.configure(api_key=api_key) self.model = genai.GenerativeModel('gemini-pro') def analyze_commercial_viability(self, coverage: str, creative_analysis: str) -> str: """Analyze commercial potential based on coverage and creative analysis""" prompt = f"""As an experienced film industry analyst, evaluate the commercial viability of this screenplay based on the following coverage and analysis. Consider: - Box office potential - Genre marketability - International appeal - Franchise potential - Current market trends - Production challenges and risks Coverage: {coverage} Creative Analysis: {creative_analysis} Provide a detailed commercial viability analysis with specific examples and market comparisons.""" try: response = self.model.generate_content(prompt) return response.text except Exception as e: logger.error(f"Error analyzing commercial viability: {str(e)}") return None def identify_target_audiences(self, coverage: str, viability_analysis: str) -> str: """Identify and analyze potential target audiences""" prompt = f"""Based on the screenplay coverage and commercial viability analysis, identify and analyze key target audiences. For each audience segment, consider: - Demographics and psychographics - Viewing habits and preferences - Marketing channels to reach them - Similar films they've supported - Potential audience size and engagement level Coverage: {coverage} Viability Analysis: {viability_analysis} Provide a detailed audience analysis with specific segments and supporting data.""" try: response = self.model.generate_content(prompt) return response.text except Exception as e: logger.error(f"Error identifying target audiences: {str(e)}") return None def analyze_comparables(self, coverage: str, target_audience: str) -> str: """Analyze comparable films and their performance""" prompt = f"""Using the screenplay coverage and target audience analysis, identify and analyze comparable films. For each comparable: - Box office performance - Budget range - Marketing approach - Release strategy - Audience reception - Critical response - What worked/didn't work Coverage: {coverage} Target Audience Analysis: {target_audience} Provide detailed analysis of 3-5 most relevant comparable films.""" try: response = self.model.generate_content(prompt) return response.text except Exception as e: logger.error(f"Error analyzing comparables: {str(e)}") return None def assess_budget_range(self, coverage: str, comparables: str) -> str: """Assess potential budget range based on content and comparables""" prompt = f"""Based on the screenplay coverage and comparable films analysis, evaluate appropriate budget ranges. Consider: - Production requirements (VFX, locations, stunts) - Cast level needed - Technical requirements - Marketing spend implications - ROI potential at different budget levels Coverage: {coverage} Comparables Analysis: {comparables} Provide detailed budget analysis with ranges and justification.""" try: response = self.model.generate_content(prompt) return response.text except Exception as e: logger.error(f"Error assessing budget: {str(e)}") return None def evaluate_marketing_angles(self, all_analyses: Dict[str, str]) -> str: """Evaluate potential marketing angles based on all previous analyses""" analyses_text = "\n\n".join([f"{k}:\n{v}" for k, v in all_analyses.items()]) prompt = f"""Based on all previous analyses, identify and evaluate key marketing angles. Consider: - Unique selling propositions - Genre hooks - Cast/talent opportunities - Visual marketing potential - Social media angles - PR opportunities - Promotional partnerships - Release timing strategies Previous Analyses: {analyses_text} Provide comprehensive marketing strategy recommendations with specific angles and approaches.""" try: response = self.model.generate_content(prompt) return response.text except Exception as e: logger.error(f"Error evaluating marketing angles: {str(e)}") return None def generate_market_analysis(self, coverage_path: Path, creative_analysis_path: Path) -> bool: """Main method to generate complete market analysis""" try: # Read input files with open(coverage_path, 'r', encoding='utf-8') as f: coverage = f.read() with open(creative_analysis_path, 'r', encoding='utf-8') as f: creative_analysis = f.read() # Generate analyses analyses = {} logger.info("Analyzing commercial viability...") analyses['commercial_viability'] = self.analyze_commercial_viability( coverage, creative_analysis) logger.info("Identifying target audiences...") analyses['target_audiences'] = self.identify_target_audiences( coverage, analyses['commercial_viability']) logger.info("Analyzing comparable films...") analyses['comparables'] = self.analyze_comparables( coverage, analyses['target_audiences']) logger.info("Assessing budget ranges...") analyses['budget_assessment'] = self.assess_budget_range( coverage, analyses['comparables']) logger.info("Evaluating marketing angles...") analyses['marketing_strategy'] = self.evaluate_marketing_angles(analyses) # Save complete analysis output_path = coverage_path.parent / "market_analysis.txt" with open(output_path, 'w', encoding='utf-8') as f: f.write("SCREENPLAY MARKET ANALYSIS\n\n") for title, content in analyses.items(): formatted_title = title.replace('_', ' ').upper() f.write(f"### {formatted_title} ###\n\n") f.write(content) f.write("\n\n") logger.info(f"Market analysis saved to: {output_path}") return True except Exception as e: logger.error(f"Error in market analysis: {str(e)}") return False