Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580import gradio as grimport osfrom typing import Dict, List, Tupleimport timeclass GlossaryGenerator:def __init__(self):self.template = """**Glossary Page Template**Use this template to create individual glossary pages for specific terms. Fill in each section with relevant information.**[TERM NAME]****1. Introduction / Brief Definition (AI Overview)*** **Purpose:** Provide the absolute clearest, most concise, and direct answer to "What is [TERM NAME]?" This should be a short, no-fluff definition, similar to an AI overview or a quick dictionary entry.* **Content:** Start immediately with the core definition. Get straight to the point.**2. Detailed Explanation*** **Purpose:** Expand on the brief definition, offering a comprehensive explanation of the term. This section should follow a "reverse pyramid" structure, meaning the most critical information is presented first, followed by supporting details.* **Content:*** **Elaborate on the core concept:** Build upon the initial definition, providing more depth and context.* **Explore related questions (PAA / Query Fans):** Anticipate what users might ask next or what related topics they might search for. Integrate answers to "People Also Ask" (PAA) type questions or expand into "query fan" concepts that naturally branch off the main term.* Provide context, background, or the purpose of the term.* Include key characteristics, functions, or processes associated with the term.* Use examples to illustrate the concept clearly.* Break down complex ideas into simpler parts.**3. Key Concepts / Components (Optional)*** **Purpose:** If the term has distinct sub-sections, components, or related key ideas that warrant separate discussion, list and explain them here.* **Content:*** Use bullet points or sub-headings for each key concept.* Briefly define and explain each component.**4. Importance / Application (Optional)*** **Purpose:** Explain why the term is significant, its impact, or how it is applied in real-world scenarios.* **Content:** Discuss the relevance, benefits, challenges, or practical uses of the term.**5. Related Terms / Concepts*** **Purpose:** Link to other relevant terms within your glossary or related concepts that readers might find useful for further understanding.* **Content:*** List terms that are closely associated or often discussed alongside the current term.**6. Sources / References*** **Purpose:** Cite the sources from which the information was gathered. This adds credibility and allows readers to explore further.* **Content:*** List URLs, book titles, or other references."""def _test_api_key(self, api_key: str) -> bool:"""Test OpenAI API key with minimal request"""if not api_key or not api_key.strip():return Falsetry:# Import here to avoid import-time issuesfrom openai import OpenAIclient = OpenAI(api_key=api_key.strip())# Test with minimal requestresponse = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "user", "content": "Hi"}],max_tokens=1)return Trueexcept Exception as e:print(f"API test error: {e}")return Falsedef _call_openai_raw(self, api_key: str, prompt: str, model: str = "gpt-4", max_tokens: int = 2000) -> str:"""Direct OpenAI API call using requests"""import requestsimport jsonif not api_key or not api_key.strip():return "π Please enter your OpenAI API key above to generate content."clean_key = api_key.strip()# Direct API call to avoid client issuesurl = "https://api.openai.com/v1/chat/completions"headers = {"Authorization": f"Bearer {clean_key}","Content-Type": "application/json"}data = {"model": model,"messages": [{"role": "system", "content": "You are a professional content writer specializing in creating high-quality glossary entries. You follow templates precisely and create comprehensive, well-structured content."},{"role": "user", "content": prompt}],"max_tokens": max_tokens,"temperature": 0.7,"top_p": 1,"frequency_penalty": 0,"presence_penalty": 0}try:print(f"π Making direct API call to OpenAI...")response = requests.post(url, headers=headers, json=data, timeout=60)print(f"π Response status: {response.status_code}")if response.status_code == 200:result = response.json()content = result['choices'][0]['message']['content'].strip()print("β API call successful")return contentelse:error_data = response.json() if response.content else {}error_msg = error_data.get('error', {}).get('message', 'Unknown error')error_code = error_data.get('error', {}).get('code', 'unknown')print(f"β API call failed: {response.status_code} - {error_msg}")if response.status_code == 401:return "β Invalid API key. Please check your OpenAI API key."elif response.status_code == 429:return "β Rate limit exceeded. Please wait a moment and try again."elif response.status_code == 404 and model == "gpt-4":# Try GPT-3.5 fallbackprint("π Trying GPT-3.5-turbo fallback...")return self._call_openai_raw(api_key, prompt, "gpt-3.5-turbo", max_tokens)elif "insufficient_quota" in error_msg.lower():return "β OpenAI API quota exceeded. Please check your billing at https://platform.openai.com/usage"else:return f"β OpenAI API Error ({response.status_code}): {error_msg}"except requests.exceptions.Timeout:return "β Request timeout. Please try again."except requests.exceptions.RequestException as e:return f"β Network error: {str(e)}"except Exception as e:return f"β Unexpected error: {str(e)}"def generate_new_content(self, api_key: str, term: str, context: str = "", target_audience: str = "general") -> str:"""Generate new glossary content for a given term"""if not term.strip():return "Please enter a term to generate content for."prompt = f"""Create a comprehensive glossary entry for the term "{term}" following this EXACT template structure:{self.template}**Requirements:**- Replace [TERM NAME] with "{term}"- Target Audience: {target_audience}- Additional Context: {context if context else "No additional context provided"}- Fill in ALL sections with relevant, accurate information- Use the "reverse pyramid" structure - most important info first- Include relevant PAA (People Also Ask) questions in section 2- Remove optional sections only if truly not applicable- Maintain clear, concise language- Provide at least 3 related terms in section 5- Include credible sources/references in section 6**Focus Areas:**- Make the brief definition crystal clear and direct- Expand thoroughly in the detailed explanation- Include practical examples and use cases- Address common questions people might have- Ensure professional, authoritative toneGenerate the complete glossary entry now:"""return self._call_openai_raw(api_key, prompt, max_tokens=2500)def update_existing_content(self, api_key: str, term: str, existing_content: str, update_instructions: str = "") -> Tuple[str, str]:"""Analyze existing content and provide update recommendations"""if not term.strip() or not existing_content.strip():return "Please provide both term and existing content.", ""# First, analyze the contentanalysis_prompt = f"""Analyze this existing glossary content for "{term}" against the template standard and provide specific improvement recommendations.**EXISTING CONTENT:**{existing_content}**TEMPLATE STANDARD:**{self.template}**UPDATE INSTRUCTIONS:** {update_instructions if update_instructions else "General content improvement"}**Provide a detailed analysis covering:**1. **STRUCTURAL ANALYSIS:**- Does it follow the template structure?- Which sections are missing or incomplete?- Is the reverse pyramid structure implemented?2. **CONTENT QUALITY ASSESSMENT:**- Clarity and conciseness of the brief definition- Depth and comprehensiveness of detailed explanation- Relevance and usefulness of examples- Quality of related terms and references3. **SPECIFIC RECOMMENDATIONS (prioritized):**- HIGH PRIORITY: Critical improvements needed- MEDIUM PRIORITY: Important enhancements- LOW PRIORITY: Nice-to-have improvements4. **SEO & USER EXPERIENCE:**- Missing PAA questions to address- Keyword opportunities- Cross-linking possibilities- Readability improvements5. **SOURCES & CREDIBILITY:**- Quality of current references- Missing authoritative sources- Fact-checking requirementsFormat as a professional content analysis report."""recommendations = self._call_openai_raw(api_key, analysis_prompt, max_tokens=1500)# Then generate updated contentupdate_prompt = f"""Create an improved version of the glossary entry for "{term}" based on the analysis and recommendations.**ORIGINAL CONTENT:**{existing_content}**ANALYSIS & RECOMMENDATIONS:**{recommendations}**TEMPLATE TO FOLLOW:**{self.template}**UPDATE INSTRUCTIONS:** {update_instructions if update_instructions else "Apply the key recommendations from the analysis"}**Create the improved glossary entry that:**1. Follows the template structure exactly2. Implements the high and medium priority recommendations3. Maintains the best elements from the original4. Adds missing sections or information5. Improves clarity, structure, and usefulness6. Includes better examples and explanations7. Enhances SEO and user experienceGenerate the complete, improved glossary entry:"""updated_content = self._call_openai_raw(api_key, update_prompt, max_tokens=2500)return recommendations, updated_contentdef create_outline_brief(self, api_key: str, topic: str, scope: str = "comprehensive") -> str:"""Create an outline or brief for new glossary content"""if not topic.strip():return "Please enter a topic for the outline."prompt = f"""Create a comprehensive content brief for developing a glossary focused on "{topic}".**Scope:** {scope}**Template Standard:** Follow the 6-section template structure provided**Create a detailed brief covering:****1. TOPIC OVERVIEW & STRATEGY**- Comprehensive topic definition and boundaries- Target audience analysis and segmentation- Content complexity and depth recommendations- Competitive landscape and differentiation opportunities**2. TERM IDENTIFICATION & PRIORITIZATION**- **Primary Terms (10-15 key terms):** Most important, high-search volume terms- **Secondary Terms (8-12 supporting terms):** Important supporting concepts- **Long-tail Terms (5-10 specific terms):** Niche but valuable terms- **Priority Matrix:** High/Medium/Low priority for each term with reasoning**3. CONTENT ARCHITECTURE**- Template section recommendations for each term type- Suggested content depth and length for each priority level- Cross-linking strategy between terms- Information hierarchy and user journey mapping**4. RESEARCH & DEVELOPMENT PLAN**- **Primary Sources:** Authoritative websites, publications, studies- **Expert Sources:** Industry leaders, academic researchers, practitioners- **User Research:** Common questions, search patterns, knowledge gaps- **Competitive Analysis:** What others are doing well/poorly**5. SEO & DISCOVERABILITY STRATEGY**- **Primary Keywords:** Main search terms for each priority level- **Long-tail Keywords:** Specific phrases users search for- **PAA Questions:** "People Also Ask" questions to address- **Content Gap Analysis:** Opportunities competitors are missing- **Internal Linking Strategy:** How terms connect to each other**6. PRODUCTION ROADMAP**- **Phase 1:** High-priority terms (timeline and resource allocation)- **Phase 2:** Secondary terms and enhancements- **Phase 3:** Long-tail terms and optimization- **Resource Requirements:** Estimated hours per term type- **Quality Assurance:** Review process and standards- **Maintenance Plan:** Update frequency and monitoring**7. SUCCESS METRICS & KPIs**- Content quality indicators- User engagement metrics- SEO performance targets- Conversion and utility measurementsCreate a comprehensive, actionable brief that will guide the entire glossary development process."""return self._call_openai_raw(api_key, prompt, max_tokens=3000)def create_gradio_interface():"""Create the Gradio interface for the glossary generator"""generator = GlossaryGenerator()def test_api_key(api_key):"""Test if the API key is valid"""if not api_key or not api_key.strip():return "β Please enter your OpenAI API key"# Basic format checkclean_key = api_key.strip()if not clean_key.startswith('sk-'):return "β Invalid format - OpenAI API keys should start with 'sk-'"if len(clean_key) < 20:return "β API key too short - check if you copied the full key"# Test the key with direct API calltest_result = generator._call_openai_raw(clean_key, "Test", "gpt-3.5-turbo", 1)if "β" in test_result:return test_resultelse:return "β API key is valid and connected!"def generate_new_wrapper(api_key, term, context, audience):if not term.strip():return "Please enter a term to generate content for."return generator.generate_new_content(api_key, term, context, audience)def update_existing_wrapper(api_key, term, existing_content, update_instructions):if not term.strip() or not existing_content.strip():return "Please provide both term and existing content.", ""recommendations, updated_content = generator.update_existing_content(api_key, term, existing_content, update_instructions)return recommendations, updated_contentdef create_outline_wrapper(api_key, topic, scope):if not topic.strip():return "Please enter a topic for the outline."return generator.create_outline_brief(api_key, topic, scope)# Create the Gradio interfacewith gr.Blocks(title="Glossary Content Generator", theme=gr.themes.Soft()) as demo:gr.Markdown("""# π Glossary Content Generator**Powered by OpenAI GPT-4** - Professional glossary content creation and optimization tool.π **Enter your OpenAI API key below to get started!**""")# API Key Sectionwith gr.Row():with gr.Column(scale=2):api_key_input = gr.Textbox(label="π OpenAI API Key",placeholder="sk-proj-... or sk-...",type="password",info="Get your API key at https://platform.openai.com/api-keys")with gr.Column(scale=1):test_key_btn = gr.Button("Test Key", variant="secondary")manual_test_btn = gr.Button("Skip Test & Try Anyway", variant="outline", size="sm")with gr.Column(scale=1):key_status = gr.Textbox(label="Status",value="β No API key provided",interactive=False,max_lines=2)def manual_override(api_key):if api_key and api_key.strip():return "β οΈ Test skipped - trying anyway..."return "β Please enter an API key first"test_key_btn.click(test_api_key,inputs=[api_key_input],outputs=[key_status])manual_test_btn.click(manual_override,inputs=[api_key_input],outputs=[key_status])gr.Markdown("---")with gr.Tabs():# Tab 1: Generate New Contentwith gr.TabItem("π Generate New Content"):gr.Markdown("### Create a new glossary entry from scratch using GPT-4")with gr.Row():with gr.Column(scale=1):new_term = gr.Textbox(label="Term to Define",placeholder="e.g., Machine Learning, CPQ, SEO, API",lines=1)new_context = gr.Textbox(label="Additional Context (Optional)",placeholder="Provide industry context, specific use cases, or background information",lines=3)new_audience = gr.Dropdown(label="Target Audience",choices=["general", "technical", "business", "beginner", "expert"],value="general")generate_btn = gr.Button("π Generate Content", variant="primary", size="lg")with gr.Column(scale=2):new_output = gr.Textbox(label="Generated Glossary Entry",lines=25,max_lines=30,show_copy_button=True)generate_btn.click(generate_new_wrapper,inputs=[api_key_input, new_term, new_context, new_audience],outputs=[new_output])# Add examplesgr.Markdown("**π‘ Example Terms:** API, Machine Learning, Blockchain, SaaS, Customer Journey, A/B Testing")# Tab 2: Update Existing Contentwith gr.TabItem("π Update Existing Content"):gr.Markdown("### Analyze and improve existing glossary entries with AI-powered recommendations")with gr.Row():with gr.Column(scale=1):update_term = gr.Textbox(label="Term Name",placeholder="Name of the term being updated",lines=1)existing_content = gr.Textbox(label="Existing Content",placeholder="Paste your current glossary entry here",lines=10)update_instructions = gr.Textbox(label="Update Instructions (Optional)",placeholder="e.g., 'Add more technical details', 'Include recent developments', 'Improve SEO focus'",lines=3)update_btn = gr.Button("π Analyze & Update", variant="primary", size="lg")with gr.Column(scale=2):with gr.Row():recommendations_output = gr.Textbox(label="π Analysis & Recommendations",lines=12,max_lines=15,show_copy_button=True)with gr.Row():updated_content_output = gr.Textbox(label="β¨ Updated Content",lines=12,max_lines=15,show_copy_button=True)update_btn.click(update_existing_wrapper,inputs=[api_key_input, update_term, existing_content, update_instructions],outputs=[recommendations_output, updated_content_output])# Tab 3: Create Outline/Briefwith gr.TabItem("π Create Content Brief"):gr.Markdown("### Generate a comprehensive strategy brief for glossary development")with gr.Row():with gr.Column(scale=1):outline_topic = gr.Textbox(label="Topic/Subject Area",placeholder="e.g., Digital Marketing, Cloud Computing, Artificial Intelligence, E-commerce",lines=1)outline_scope = gr.Dropdown(label="Scope & Depth",choices=["comprehensive", "focused", "basic", "advanced", "specialized"],value="comprehensive")outline_btn = gr.Button("π Create Strategic Brief", variant="primary", size="lg")with gr.Column(scale=2):outline_output = gr.Textbox(label="π Content Strategy Brief",lines=25,max_lines=30,show_copy_button=True)outline_btn.click(create_outline_wrapper,inputs=[api_key_input, outline_topic, outline_scope],outputs=[outline_output])gr.Markdown("**π‘ Example Topics:** Digital Marketing, FinTech, SaaS Operations, Data Science, Cybersecurity")# Tab 4: Template Referencewith gr.TabItem("π Template Reference"):gr.Markdown("### Official Glossary Template Structure")template_display = gr.Textbox(label="Template Guidelines",value=generator.template,lines=35,max_lines=40,interactive=False,show_copy_button=True)gr.Markdown("""---## π§ How to Get Your OpenAI API Key:1. **Visit** [platform.openai.com/api-keys](https://platform.openai.com/api-keys)2. **Sign up** or log in to your OpenAI account3. **Add billing information** (GPT-4 requires a paid account)4. **Create a new secret key**5. **Copy and paste** it into the field above## π° **Cost Information:**- **GPT-4 pricing**: ~$0.03 per 1K input tokens, ~$0.06 per 1K output tokens- **Per generation**: Approximately $0.02-0.10 depending on content length- **Very cost-effective** for professional content creation## β¨ **Features:**- π€ **GPT-4 Powered**: High-quality, professional content generation- π **Template Consistency**: Follows your exact 6-section structure- π **Content Analysis**: Detailed improvement recommendations- π **Strategic Planning**: Comprehensive content briefs and roadmaps- π― **SEO Optimized**: Includes PAA questions and keyword strategies- π **Copy-Friendly**: Easy copy buttons for all outputs- π **No Setup Required**: Just enter your API key and start generating!- π οΈ **Direct API**: Uses raw HTTP requests to avoid library conflicts""")return demo# Launch the applicationif __name__ == "__main__":app = create_gradio_interface()app.launch(share=False,server_name="0.0.0.0",server_port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import timeimport requestsimport jsonfrom typing import Optionaldef _call_openai_with_retry(self, api_key: str, prompt: str, model: str = "gpt-4", max_tokens: int = 2000, max_retries: int = 3) -> str:"""OpenAI API call with exponential backoff retry logic"""if not api_key or not api_key.strip():return "π Please enter your OpenAI API key above to generate content."clean_key = api_key.strip()url = "https://api.openai.com/v1/chat/completions"headers = {"Authorization": f"Bearer {clean_key}","Content-Type": "application/json"}# Start with GPT-3.5-turbo if GPT-4 is not availablemodels_to_try = [model]if model == "gpt-4":models_to_try = ["gpt-4", "gpt-3.5-turbo"]for current_model in models_to_try:print(f"π€ Trying model: {current_model}")data = {"model": current_model,"messages": [{"role": "system", "content": "You are a professional content writer specializing in creating high-quality glossary entries."},{"role": "user", "content": prompt}],"max_tokens": max_tokens,"temperature": 0.7}for attempt in range(max_retries):try:print(f"π‘ Attempt {attempt + 1}/{max_retries} for {current_model}")response = requests.post(url, headers=headers, json=data, timeout=60)if response.status_code == 200:result = response.json()content = result['choices'][0]['message']['content'].strip()print(f"β Success with {current_model}")return contentelif response.status_code == 429:# Rate limit hittry:error_data = response.json()error_msg = error_data.get('error', {}).get('message', '')except:error_msg = "Rate limit exceeded"print(f"β³ Rate limit hit: {error_msg}")# Extract wait time from headers or use exponential backoffretry_after = response.headers.get('retry-after')if retry_after:wait_time = int(retry_after)print(f"β° Waiting {wait_time} seconds as suggested by API...")else:wait_time = (2 ** attempt) * 2 # Exponential backoff: 2, 4, 8 secondsprint(f"β° Waiting {wait_time} seconds (exponential backoff)...")if attempt < max_retries - 1: # Don't wait on the last attempttime.sleep(wait_time)continueelse:return f"β Rate limit exceeded after {max_retries} attempts. Please wait a few minutes and try again."elif response.status_code == 401:return "β Invalid API key. Please check your OpenAI API key."elif response.status_code == 404:print(f"β Model {current_model} not available, trying next...")break # Try next modelelse:# Other errorstry:error_data = response.json()error_msg = error_data.get('error', {}).get('message', 'Unknown error')except:error_msg = f"HTTP {response.status_code}"if "insufficient_quota" in error_msg.lower():return "β OpenAI API quota exceeded. Please check your billing at https://platform.openai.com/usage"print(f"β API Error: {error_msg}")if attempt < max_retries - 1:time.sleep(2) # Short wait for other errorscontinueelse:return f"β API Error: {error_msg}"except requests.exceptions.Timeout:print(f"β° Request timeout on attempt {attempt + 1}")if attempt < max_retries - 1:time.sleep(2)continueelse:return "β Request timeout after multiple attempts. Please try again."except Exception as e:print(f"β Unexpected error on attempt {attempt + 1}: {str(e)}")if attempt < max_retries - 1:time.sleep(2)continueelse:return f"β Unexpected error: {str(e)}"return "β All models failed. Please check your API key and try again."# Also add a rate limit checkerdef check_rate_limits(self, api_key: str) -> str:"""Check current rate limit status"""try:# Make a minimal request to check statusresponse = self._call_openai_with_retry(api_key, "test", "gpt-3.5-turbo", 1)if "Rate limit" in response:return "β Currently rate limited"elif "β" in response:return responseelse:return "β Rate limits OK"except Exception as e:return f"β Error checking rate limits: {str(e)}"
app.py+110-559