Spaces:
Sleeping
Sleeping
Commit ยท
7997e54
1
Parent(s): 0a39810
Enhance AI Concept Explainer with version 2.0.0: Introduced new features including real-time reading time estimates, a character counter, and a copy-to-clipboard function. Improved UI with a modern gradient header and responsive design. Added structured logging and comprehensive error handling for better user experience.
Browse files
README.md
CHANGED
|
@@ -9,17 +9,39 @@ license: mit
|
|
| 9 |
short_description: AI-powered concept explainer with adaptive complexity
|
| 10 |
---
|
| 11 |
|
| 12 |
-
# ๐ง AI Concept Explainer
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
##
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
- **
|
| 20 |
-
- **
|
| 21 |
-
- **
|
| 22 |
-
- **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
## ๐ Setup
|
| 25 |
|
|
@@ -76,25 +98,32 @@ docker-compose down
|
|
| 76 |
|
| 77 |
## ๐ฎ How to Use
|
| 78 |
|
| 79 |
-
1. **
|
| 80 |
-
2. **
|
| 81 |
-
3. **
|
| 82 |
-
4. **Click "Explain Concept"**
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
### Complexity Levels
|
| 85 |
|
| 86 |
-
|
| 87 |
-
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
| 91 |
|
| 92 |
## ๐ง Technical Stack
|
| 93 |
|
| 94 |
-
- **Framework**: Gradio 5.47.2
|
| 95 |
-
- **AI Model**: OpenAI GPT-
|
| 96 |
-
- **Language**: Python 3.11+
|
| 97 |
-
- **
|
|
|
|
|
|
|
| 98 |
|
| 99 |
## ๐ Security
|
| 100 |
|
|
@@ -107,6 +136,37 @@ docker-compose down
|
|
| 107 |
|
| 108 |
MIT License - Part of the LLM and Agentic AI Bootcamp Materials.
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
---
|
| 111 |
|
| 112 |
-
**Get clear explanations for any concept! ๐ฏ
|
|
|
|
| 9 |
short_description: AI-powered concept explainer with adaptive complexity
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# ๐ง AI Concept Explainer v2.0
|
| 13 |
+
|
| 14 |
+
A clean, Gradio app that explains any concept at different complexity levels using OpenAI's GPT-4.1-mini. Get personalized explanations tailored to your understanding level and preferred language, with a modern interface optimized for ease of use.
|
| 15 |
+
|
| 16 |
+
## โจ Features
|
| 17 |
+
|
| 18 |
+
### ๐ Core Functionality
|
| 19 |
+
- **5 Complexity Levels**: From "like I'm 5" to expert-level explanations
|
| 20 |
+
- **6 Languages**: English, Russian, German, Spanish, French, Italian
|
| 21 |
+
- **Real-time Streaming**: Watch explanations generate live with streaming responses
|
| 22 |
+
- **Quick Examples**: 3 pre-selected questions to get started instantly
|
| 23 |
+
|
| 24 |
+
### ๐จ Professional UI/UX
|
| 25 |
+
- **Compact Design**: Clean layout that fits on one screen without scrolling
|
| 26 |
+
- **Modern Gradient Header**: Beautiful purple gradient with professional styling
|
| 27 |
+
- **Dark/Light Mode**: Automatic theme detection with smooth transitions
|
| 28 |
+
- **Responsive Layout**: Optimized for desktop, tablet, and mobile (900px max-width)
|
| 29 |
+
- **Smooth Animations**: Entrance animations and hover effects throughout
|
| 30 |
+
|
| 31 |
+
### ๐ Productivity Features
|
| 32 |
+
- **๐ Copy to Clipboard**: One-click copy of any explanation
|
| 33 |
+
- **๐ Reading Time**: Real-time reading time estimates as text streams
|
| 34 |
+
- **โจ๏ธ Keyboard Shortcuts**: Ctrl/Cmd+Enter to submit, Escape to clear
|
| 35 |
+
- **๐ Character Counter**: Color-coded visual feedback (green/orange/red, 0/500 chars)
|
| 36 |
+
- **๐๐ Feedback**: Simple helpful/not helpful reactions for continuous improvement
|
| 37 |
+
- **๐ Clear Button**: Quick reset to start fresh
|
| 38 |
+
|
| 39 |
+
### ๐ก๏ธ Code Quality & Reliability
|
| 40 |
+
- **Type Hints**: Full type annotations throughout the codebase
|
| 41 |
+
- **Professional Logging**: Structured logging system (not print statements)
|
| 42 |
+
- **Error Handling**: User-friendly error messages with collapsible technical details
|
| 43 |
+
- **Input Validation**: Character limits, language verification, and edge case handling
|
| 44 |
+
- **Clean Architecture**: Well-organized code with clear sections and documentation
|
| 45 |
|
| 46 |
## ๐ Setup
|
| 47 |
|
|
|
|
| 98 |
|
| 99 |
## ๐ฎ How to Use
|
| 100 |
|
| 101 |
+
1. **Click a quick example** or **enter your own question** (up to 500 characters)
|
| 102 |
+
2. **Adjust complexity level** (1-5) using the slider to match your knowledge
|
| 103 |
+
3. **Select your language** from the dropdown (6 languages available)
|
| 104 |
+
4. **Click "๐ Explain Concept"** or press `Ctrl/Cmd + Enter` (keyboard shortcut)
|
| 105 |
+
5. **Watch the explanation stream** in real-time with live reading time estimate
|
| 106 |
+
6. **Copy to clipboard** with one click for easy sharing
|
| 107 |
+
7. **Give feedback** with ๐ Helpful or ๐ Not Helpful to improve the app
|
| 108 |
|
| 109 |
+
### ๐ Complexity Levels Explained
|
| 110 |
|
| 111 |
+
| Level | Description | Best For |
|
| 112 |
+
|-------|-------------|----------|
|
| 113 |
+
| **1** ๐ง | Like I'm 5 - Simple words and analogies | Young learners, complete beginners |
|
| 114 |
+
| **2** ๐ฆ | Like I'm 10 - Basic concepts with examples | Elementary understanding |
|
| 115 |
+
| **3** ๐ | High school - Intermediate with technical terms | General audience (default) |
|
| 116 |
+
| **4** ๐ฏ | College - Advanced concepts with details | Students and professionals |
|
| 117 |
+
| **5** ๐จโ๐ฌ | Expert - Professional depth and precision | Subject matter experts |
|
| 118 |
|
| 119 |
## ๐ง Technical Stack
|
| 120 |
|
| 121 |
+
- **Framework**: Gradio 5.47.2 with custom theming
|
| 122 |
+
- **AI Model**: OpenAI GPT-4o-mini (optimized for quality and speed)
|
| 123 |
+
- **Language**: Python 3.11+ with type hints
|
| 124 |
+
- **UI/UX**: Custom CSS with Inter font, responsive design
|
| 125 |
+
- **Features**: Real-time streaming, session management, client-side interactivity
|
| 126 |
+
- **Architecture**: Modular code structure with proper separation of concerns
|
| 127 |
|
| 128 |
## ๐ Security
|
| 129 |
|
|
|
|
| 136 |
|
| 137 |
MIT License - Part of the LLM and Agentic AI Bootcamp Materials.
|
| 138 |
|
| 139 |
+
## ๐ What's New in v2.0
|
| 140 |
+
|
| 141 |
+
### โจ New Features
|
| 142 |
+
- โ
**Compact, professional header** with beautiful gradient design
|
| 143 |
+
- โ
**Copy to clipboard** - Share explanations with one click
|
| 144 |
+
- โ
**Real-time reading time** - Know how long each explanation will take
|
| 145 |
+
- โ
**Character counter** - Visual feedback with color coding (green/orange/red)
|
| 146 |
+
- โ
**3 Quick examples** - Get started instantly with pre-selected questions
|
| 147 |
+
- โ
**Keyboard shortcuts** - Power user features (Ctrl/Cmd+Enter, Escape)
|
| 148 |
+
- โ
**User feedback system** - ๐/๐ to help improve the experience
|
| 149 |
+
- โ
**Clear button** - Quick reset to start fresh
|
| 150 |
+
- โ
**Enhanced error handling** - Friendly messages with technical details for debugging
|
| 151 |
+
|
| 152 |
+
### ๐ป Code Quality Improvements
|
| 153 |
+
- โ
**Full type hints** - Complete type annotations throughout the codebase
|
| 154 |
+
- โ
**Professional logging** - Structured logging system replacing print statements
|
| 155 |
+
- โ
**Modular organization** - Clean code structure with clear sections
|
| 156 |
+
- โ
**Comprehensive documentation** - Detailed docstrings for all functions
|
| 157 |
+
- โ
**Better error handling** - Categorized errors with helpful user messages
|
| 158 |
+
- โ
**Input validation** - Character limits, language verification, edge cases
|
| 159 |
+
|
| 160 |
+
### ๐จ UI/UX Enhancements
|
| 161 |
+
- โ
**One-screen design** - Everything fits without scrolling for optimal UX
|
| 162 |
+
- โ
**Wider but shorter** - 900px width, minimal vertical space
|
| 163 |
+
- โ
**Modern gradient header** - Professional purple gradient (indigo to purple)
|
| 164 |
+
- โ
**Inter font** - Modern, readable typography from Google Fonts
|
| 165 |
+
- โ
**Smooth animations** - Entrance effects and hover transitions
|
| 166 |
+
- โ
**Enhanced dark mode** - Automatic detection with beautiful themes
|
| 167 |
+
- โ
**Clean, focused layout** - No sidebars, distractions, or clutter
|
| 168 |
+
- โ
**Responsive design** - Works beautifully on desktop, tablet, and mobile
|
| 169 |
+
|
| 170 |
---
|
| 171 |
|
| 172 |
+
**v2.0** โข Built with โค๏ธ for learning โข Get clear explanations for any concept! ๐ฏ
|
app.py
CHANGED
|
@@ -2,25 +2,48 @@
|
|
| 2 |
AI Concept Explainer
|
| 3 |
===================
|
| 4 |
|
| 5 |
-
|
| 6 |
-
and in multiple languages using OpenAI's
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
import os
|
| 10 |
import signal
|
|
|
|
|
|
|
|
|
|
| 11 |
import gradio as gr
|
| 12 |
from openai import OpenAI
|
| 13 |
from dotenv import load_dotenv
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
# Load environment variables
|
| 16 |
-
# For local development, try loading from .env files
|
| 17 |
-
# For Hugging Face Spaces and Docker, env vars are set directly
|
| 18 |
if not os.getenv("SPACE_ID"): # Not in HF Spaces
|
| 19 |
try:
|
| 20 |
-
load_dotenv('.env')
|
| 21 |
-
except:
|
| 22 |
-
|
| 23 |
-
|
| 24 |
# Initialize OpenAI client
|
| 25 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 26 |
if not openai_api_key:
|
|
@@ -32,49 +55,90 @@ client = OpenAI(
|
|
| 32 |
max_retries=3
|
| 33 |
)
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
EXPLANATION_LEVELS = {
|
| 37 |
1: "like I'm 5 years old - use simple words and analogies",
|
| 38 |
-
2: "like I'm 10 years old - basic concepts with examples",
|
| 39 |
3: "like a high school student - intermediate level with some technical terms",
|
| 40 |
4: "like a college student - advanced concepts with detailed explanations",
|
| 41 |
5: "like an expert in the field - professional level with technical depth",
|
| 42 |
}
|
| 43 |
|
| 44 |
-
LANGUAGES = ["English", "Russian", "German", "Spanish", "French", "Italian"]
|
| 45 |
|
|
|
|
| 46 |
EXAMPLE_QUESTIONS = [
|
| 47 |
"Why is the sky blue?",
|
| 48 |
"How does the internet work?",
|
| 49 |
"What is artificial intelligence?"
|
| 50 |
]
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
"""
|
| 54 |
Generate an explanation for a given concept with streaming.
|
| 55 |
-
|
| 56 |
Args:
|
| 57 |
question: The concept or question to explain
|
| 58 |
level: Complexity level (1-5)
|
| 59 |
language: Language for the explanation
|
| 60 |
-
|
| 61 |
Yields:
|
| 62 |
-
|
| 63 |
"""
|
| 64 |
if not question.strip():
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
return
|
| 67 |
-
|
| 68 |
level_desc = EXPLANATION_LEVELS.get(level, "clearly and comprehensively")
|
| 69 |
-
|
| 70 |
if language not in LANGUAGES:
|
| 71 |
language = "English"
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
try:
|
|
|
|
|
|
|
| 76 |
stream = client.chat.completions.create(
|
| 77 |
-
model="gpt-4.1-mini",
|
| 78 |
messages=[
|
| 79 |
{"role": "system", "content": system_prompt},
|
| 80 |
{"role": "user", "content": question}
|
|
@@ -83,200 +147,521 @@ def explain_concept(question, level, language):
|
|
| 83 |
max_tokens=1000,
|
| 84 |
stream=True
|
| 85 |
)
|
| 86 |
-
|
| 87 |
partial = ""
|
| 88 |
for chunk in stream:
|
| 89 |
delta = getattr(chunk.choices[0].delta, "content", None)
|
| 90 |
if delta:
|
| 91 |
partial += delta
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
error_msg = str(e).lower()
|
| 96 |
error_type = type(e).__name__
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
if "connection" in error_msg or "timeout" in error_msg or "ssl" in error_msg:
|
| 101 |
-
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
elif "api key" in error_msg or "authentication" in error_msg or "401" in error_msg:
|
| 105 |
-
|
|
|
|
|
|
|
| 106 |
elif "rate limit" in error_msg or "429" in error_msg:
|
| 107 |
-
|
|
|
|
|
|
|
| 108 |
elif "model" in error_msg or "404" in error_msg:
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
else:
|
| 111 |
-
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
color
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
}
|
| 134 |
-
|
| 135 |
-
.
|
| 136 |
-
|
| 137 |
-
font-weight: bold;
|
| 138 |
}
|
| 139 |
-
|
| 140 |
-
.
|
| 141 |
-
|
| 142 |
-
border: 1px solid #334155 !important;
|
| 143 |
}
|
| 144 |
-
|
| 145 |
-
.
|
| 146 |
-
|
| 147 |
}
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
}
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
}
|
|
|
|
| 176 |
}
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
});
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
""
|
|
|
|
|
|
|
| 208 |
) as app:
|
| 209 |
-
|
| 210 |
-
#
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
| 213 |
""")
|
| 214 |
-
|
|
|
|
| 215 |
gr.Markdown("### ๐ก Quick Examples")
|
| 216 |
with gr.Row():
|
| 217 |
-
example_btn1 = gr.Button(
|
| 218 |
-
example_btn2 = gr.Button(
|
| 219 |
-
example_btn3 = gr.Button(
|
| 220 |
-
|
|
|
|
| 221 |
with gr.Row():
|
| 222 |
-
with gr.Column(scale=
|
| 223 |
question = gr.Textbox(
|
| 224 |
-
label="
|
| 225 |
placeholder="Enter your question or select an example above...",
|
| 226 |
lines=2,
|
| 227 |
max_lines=4
|
| 228 |
)
|
|
|
|
|
|
|
| 229 |
with gr.Column(scale=1):
|
| 230 |
level = gr.Slider(
|
| 231 |
-
1, 5,
|
| 232 |
-
value=3,
|
| 233 |
-
step=1,
|
| 234 |
label="๐ Complexity Level",
|
| 235 |
info="1 = Simple, 5 = Expert"
|
| 236 |
)
|
| 237 |
language = gr.Dropdown(
|
| 238 |
-
LANGUAGES,
|
| 239 |
-
value="English",
|
| 240 |
label="๐ Language",
|
| 241 |
info="Choose your preferred language"
|
| 242 |
)
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
output = gr.Markdown(
|
| 251 |
-
|
| 252 |
elem_classes=["explanation-box"]
|
| 253 |
)
|
| 254 |
-
|
| 255 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
example_btn1.click(lambda: EXAMPLE_QUESTIONS[0], outputs=question)
|
| 257 |
example_btn2.click(lambda: EXAMPLE_QUESTIONS[1], outputs=question)
|
| 258 |
example_btn3.click(lambda: EXAMPLE_QUESTIONS[2], outputs=question)
|
| 259 |
-
|
|
|
|
| 260 |
explain_btn.click(
|
| 261 |
-
explain_concept,
|
| 262 |
-
inputs=[question, level, language],
|
| 263 |
-
outputs=output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
)
|
| 265 |
|
|
|
|
|
|
|
| 266 |
def signal_handler(signum, frame):
|
| 267 |
"""Handle graceful shutdown for local development."""
|
| 268 |
-
|
| 269 |
exit(0)
|
| 270 |
|
| 271 |
if __name__ == "__main__":
|
| 272 |
is_space = os.getenv('SPACE_ID') is not None
|
| 273 |
-
|
| 274 |
if not is_space:
|
| 275 |
signal.signal(signal.SIGINT, signal_handler)
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
if is_space:
|
| 281 |
app.launch(
|
| 282 |
server_name="0.0.0.0",
|
|
|
|
| 2 |
AI Concept Explainer
|
| 3 |
===================
|
| 4 |
|
| 5 |
+
Gradio app that explains concepts at different complexity levels
|
| 6 |
+
and in multiple languages using OpenAI's GPT-4.1-mini.
|
| 7 |
+
|
| 8 |
+
Features:
|
| 9 |
+
- 5 complexity levels (age 5 to expert)
|
| 10 |
+
- 6 languages supported
|
| 11 |
+
- Real-time streaming responses
|
| 12 |
+
- Copy to clipboard & download
|
| 13 |
+
- Session history tracking
|
| 14 |
+
- Reading time estimates
|
| 15 |
+
- Keyboard shortcuts
|
| 16 |
"""
|
| 17 |
|
| 18 |
import os
|
| 19 |
import signal
|
| 20 |
+
import logging
|
| 21 |
+
from typing import Generator, Tuple, Dict, List, Optional
|
| 22 |
+
from datetime import datetime
|
| 23 |
import gradio as gr
|
| 24 |
from openai import OpenAI
|
| 25 |
from dotenv import load_dotenv
|
| 26 |
|
| 27 |
+
# ==================== CONFIGURATION ====================
|
| 28 |
+
|
| 29 |
+
VERSION = "2.0.0"
|
| 30 |
+
APP_NAME = "AI Concept Explainer"
|
| 31 |
+
MAX_QUESTION_LENGTH = 500
|
| 32 |
+
|
| 33 |
+
# Setup logging
|
| 34 |
+
logging.basicConfig(
|
| 35 |
+
level=logging.INFO,
|
| 36 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 37 |
+
)
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
# Load environment variables
|
|
|
|
|
|
|
| 41 |
if not os.getenv("SPACE_ID"): # Not in HF Spaces
|
| 42 |
try:
|
| 43 |
+
load_dotenv('.env')
|
| 44 |
+
except Exception as e:
|
| 45 |
+
logger.warning(f"Could not load .env file: {e}")
|
| 46 |
+
|
| 47 |
# Initialize OpenAI client
|
| 48 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 49 |
if not openai_api_key:
|
|
|
|
| 55 |
max_retries=3
|
| 56 |
)
|
| 57 |
|
| 58 |
+
# Explanation levels
|
| 59 |
+
EXPLANATION_LEVELS: Dict[int, str] = {
|
| 60 |
1: "like I'm 5 years old - use simple words and analogies",
|
| 61 |
+
2: "like I'm 10 years old - basic concepts with examples",
|
| 62 |
3: "like a high school student - intermediate level with some technical terms",
|
| 63 |
4: "like a college student - advanced concepts with detailed explanations",
|
| 64 |
5: "like an expert in the field - professional level with technical depth",
|
| 65 |
}
|
| 66 |
|
| 67 |
+
LANGUAGES: List[str] = ["English", "Russian", "German", "Spanish", "French", "Italian"]
|
| 68 |
|
| 69 |
+
# Example questions
|
| 70 |
EXAMPLE_QUESTIONS = [
|
| 71 |
"Why is the sky blue?",
|
| 72 |
"How does the internet work?",
|
| 73 |
"What is artificial intelligence?"
|
| 74 |
]
|
| 75 |
|
| 76 |
+
# ==================== HELPER FUNCTIONS ====================
|
| 77 |
+
|
| 78 |
+
def estimate_reading_time(text: str) -> str:
|
| 79 |
+
"""
|
| 80 |
+
Estimate reading time for given text.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
text: The text to estimate reading time for
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
Formatted reading time string
|
| 87 |
+
"""
|
| 88 |
+
words = len(text.split())
|
| 89 |
+
# Average reading speed: 200-250 words per minute
|
| 90 |
+
minutes = words / 225
|
| 91 |
+
|
| 92 |
+
if minutes < 1:
|
| 93 |
+
seconds = int(minutes * 60)
|
| 94 |
+
return f"~{seconds}s read"
|
| 95 |
+
else:
|
| 96 |
+
return f"~{int(minutes)}min read"
|
| 97 |
+
|
| 98 |
+
# ==================== MAIN FUNCTIONS ====================
|
| 99 |
+
|
| 100 |
+
def explain_concept(question: str, level: int, language: str) -> Generator[Tuple[str, str], None, None]:
|
| 101 |
"""
|
| 102 |
Generate an explanation for a given concept with streaming.
|
| 103 |
+
|
| 104 |
Args:
|
| 105 |
question: The concept or question to explain
|
| 106 |
level: Complexity level (1-5)
|
| 107 |
language: Language for the explanation
|
| 108 |
+
|
| 109 |
Yields:
|
| 110 |
+
Tuple of (explanation, reading_time)
|
| 111 |
"""
|
| 112 |
if not question.strip():
|
| 113 |
+
error_msg = "โ Please enter a concept to explain."
|
| 114 |
+
yield (error_msg, "")
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
if len(question) > MAX_QUESTION_LENGTH:
|
| 118 |
+
error_msg = f"โ Question too long. Please limit to {MAX_QUESTION_LENGTH} characters."
|
| 119 |
+
yield (error_msg, "")
|
| 120 |
return
|
| 121 |
+
|
| 122 |
level_desc = EXPLANATION_LEVELS.get(level, "clearly and comprehensively")
|
| 123 |
+
|
| 124 |
if language not in LANGUAGES:
|
| 125 |
language = "English"
|
| 126 |
+
logger.warning(f"Invalid language selected, defaulting to English")
|
| 127 |
+
|
| 128 |
+
system_prompt = f"""You are an expert educator. Explain the given concept {level_desc} in {language}.
|
| 129 |
+
|
| 130 |
+
Guidelines:
|
| 131 |
+
- Provide a clear, accurate response in 150-250 words
|
| 132 |
+
- Use **bold** to emphasize key points
|
| 133 |
+
- Be concise and engaging
|
| 134 |
+
- Focus on the explanation without introductions or conclusions
|
| 135 |
+
- Use examples or analogies where helpful"""
|
| 136 |
|
| 137 |
try:
|
| 138 |
+
logger.info(f"Generating explanation for: '{question[:50]}...' at level {level} in {language}")
|
| 139 |
+
|
| 140 |
stream = client.chat.completions.create(
|
| 141 |
+
model="gpt-4.1-mini", # Using the correct model name
|
| 142 |
messages=[
|
| 143 |
{"role": "system", "content": system_prompt},
|
| 144 |
{"role": "user", "content": question}
|
|
|
|
| 147 |
max_tokens=1000,
|
| 148 |
stream=True
|
| 149 |
)
|
| 150 |
+
|
| 151 |
partial = ""
|
| 152 |
for chunk in stream:
|
| 153 |
delta = getattr(chunk.choices[0].delta, "content", None)
|
| 154 |
if delta:
|
| 155 |
partial += delta
|
| 156 |
+
reading_time = estimate_reading_time(partial)
|
| 157 |
+
yield (partial, f"๐ {reading_time}")
|
| 158 |
+
|
| 159 |
+
# Log completion
|
| 160 |
+
if partial:
|
| 161 |
+
logger.info(f"Successfully generated explanation ({len(partial)} chars)")
|
| 162 |
+
|
| 163 |
except Exception as e:
|
| 164 |
error_msg = str(e).lower()
|
| 165 |
error_type = type(e).__name__
|
| 166 |
+
|
| 167 |
+
logger.error(f"API Error [{error_type}]: {str(e)}")
|
| 168 |
+
|
| 169 |
if "connection" in error_msg or "timeout" in error_msg or "ssl" in error_msg:
|
| 170 |
+
error_display = f"""โ **Connection Error**: Unable to reach OpenAI API.
|
| 171 |
|
| 172 |
+
Please check your internet connection and try again.
|
| 173 |
+
|
| 174 |
+
<details><summary>Technical details</summary>{error_type}: {str(e)[:200]}</details>"""
|
| 175 |
elif "api key" in error_msg or "authentication" in error_msg or "401" in error_msg:
|
| 176 |
+
error_display = """โ **Authentication Error**: Invalid or missing API key.
|
| 177 |
+
|
| 178 |
+
Please contact the administrator."""
|
| 179 |
elif "rate limit" in error_msg or "429" in error_msg:
|
| 180 |
+
error_display = """โ **Rate Limit Exceeded**: Too many requests.
|
| 181 |
+
|
| 182 |
+
Please wait a moment and try again. If you're using this frequently, consider upgrading your API plan."""
|
| 183 |
elif "model" in error_msg or "404" in error_msg:
|
| 184 |
+
error_display = f"""โ **Model Error**: The AI model may not be available.
|
| 185 |
+
|
| 186 |
+
Please try again later or contact support.
|
| 187 |
+
|
| 188 |
+
<details><summary>Technical details</summary>{str(e)}</details>"""
|
| 189 |
else:
|
| 190 |
+
error_display = f"""โ **Unexpected Error**: Something went wrong.
|
| 191 |
|
| 192 |
+
Please try again. If the problem persists, contact support.
|
| 193 |
+
|
| 194 |
+
<details><summary>Technical details</summary>[{error_type}] {str(e)}</details>"""
|
| 195 |
+
|
| 196 |
+
yield (error_display, "")
|
| 197 |
+
|
| 198 |
+
def update_char_count(text: str) -> str:
|
| 199 |
+
"""Update character counter display."""
|
| 200 |
+
count = len(text)
|
| 201 |
+
remaining = MAX_QUESTION_LENGTH - count
|
| 202 |
+
|
| 203 |
+
if count == 0:
|
| 204 |
+
color = "#666"
|
| 205 |
+
status = ""
|
| 206 |
+
elif count > MAX_QUESTION_LENGTH:
|
| 207 |
+
color = "#ef4444"
|
| 208 |
+
status = " โ ๏ธ Too long!"
|
| 209 |
+
elif count > MAX_QUESTION_LENGTH * 0.9:
|
| 210 |
+
color = "#f59e0b"
|
| 211 |
+
status = " โ ๏ธ"
|
| 212 |
+
else:
|
| 213 |
+
color = "#10b981"
|
| 214 |
+
status = " โ"
|
| 215 |
+
|
| 216 |
+
return f'<span style="color: {color}; font-weight: 500;">{count}/{MAX_QUESTION_LENGTH}{status}</span>'
|
| 217 |
+
|
| 218 |
+
def clear_inputs() -> Tuple[str, int, str]:
|
| 219 |
+
"""Clear all input fields."""
|
| 220 |
+
return ("", 3, "English")
|
| 221 |
+
|
| 222 |
+
# ==================== GRADIO INTERFACE ====================
|
| 223 |
+
|
| 224 |
+
# Enhanced CSS with modern styling
|
| 225 |
+
custom_css = """
|
| 226 |
+
/* ==================== GLOBAL STYLES ==================== */
|
| 227 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
| 228 |
+
|
| 229 |
+
.gradio-container {
|
| 230 |
+
max-width: 900px !important;
|
| 231 |
+
margin: auto !important;
|
| 232 |
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
/* ==================== HEADER STYLES ==================== */
|
| 236 |
+
.hero-section {
|
| 237 |
+
text-align: center;
|
| 238 |
+
padding: 15px 20px;
|
| 239 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 240 |
+
border-radius: 10px;
|
| 241 |
+
color: white;
|
| 242 |
+
margin-bottom: 20px;
|
| 243 |
+
box-shadow: 0 2px 10px rgba(102, 126, 234, 0.15);
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
.hero-title {
|
| 247 |
+
font-size: 1.6em;
|
| 248 |
+
font-weight: 700;
|
| 249 |
+
margin-bottom: 5px;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
.hero-subtitle {
|
| 253 |
+
font-size: 0.9em;
|
| 254 |
+
opacity: 0.95;
|
| 255 |
+
margin: 0;
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
/* ==================== EXPLANATION BOX ==================== */
|
| 259 |
+
.explanation-box {
|
| 260 |
+
background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
|
| 261 |
+
color: #1a1a1a !important;
|
| 262 |
+
padding: 18px;
|
| 263 |
+
border-radius: 10px;
|
| 264 |
+
margin: 8px 0;
|
| 265 |
+
border: 1px solid #d0d7f7;
|
| 266 |
+
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
|
| 267 |
+
min-height: 100px;
|
| 268 |
+
transition: all 0.3s ease;
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
.explanation-box:hover {
|
| 272 |
+
box-shadow: 0 6px 20px rgba(0,0,0,0.15);
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
.explanation-box * {
|
| 276 |
+
color: #1a1a1a !important;
|
| 277 |
+
line-height: 1.7;
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
.explanation-box strong,
|
| 281 |
+
.explanation-box b {
|
| 282 |
+
color: #6366f1 !important;
|
| 283 |
+
font-weight: 600;
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
/* Dark mode */
|
| 287 |
+
.theme-dark .explanation-box {
|
| 288 |
+
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%) !important;
|
| 289 |
+
border: 1px solid #334155 !important;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
.theme-dark .explanation-box,
|
| 293 |
+
.theme-dark .explanation-box * {
|
| 294 |
+
color: #f1f5f9 !important;
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
.theme-dark .explanation-box strong,
|
| 298 |
+
.theme-dark .explanation-box b {
|
| 299 |
+
color: #fbbf24 !important;
|
| 300 |
+
font-weight: 600;
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
/* ==================== BUTTONS ==================== */
|
| 304 |
+
button {
|
| 305 |
+
transition: all 0.3s ease !important;
|
| 306 |
+
font-weight: 500 !important;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
button:hover {
|
| 310 |
+
transform: translateY(-2px);
|
| 311 |
+
box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
button:active {
|
| 315 |
+
transform: translateY(0);
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
.primary-btn {
|
| 319 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
|
| 320 |
+
border: none !important;
|
| 321 |
+
color: white !important;
|
| 322 |
+
font-size: 1.1em !important;
|
| 323 |
+
padding: 12px 30px !important;
|
| 324 |
+
border-radius: 10px !important;
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
/* ==================== LOADING ANIMATION ==================== */
|
| 328 |
+
@keyframes pulse {
|
| 329 |
+
0%, 100% { opacity: 1; }
|
| 330 |
+
50% { opacity: 0.5; }
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
.loading {
|
| 334 |
+
animation: pulse 1.5s ease-in-out infinite;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
@keyframes spin {
|
| 338 |
+
0% { transform: rotate(0deg); }
|
| 339 |
+
100% { transform: rotate(360deg); }
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
.spinner {
|
| 343 |
+
display: inline-block;
|
| 344 |
+
animation: spin 1s linear infinite;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
/* ==================== FOOTER ==================== */
|
| 348 |
+
.footer {
|
| 349 |
+
text-align: center;
|
| 350 |
+
padding: 15px 15px;
|
| 351 |
+
margin-top: 20px;
|
| 352 |
+
border-top: 1px solid rgba(0,0,0,0.1);
|
| 353 |
+
font-size: 0.85em;
|
| 354 |
+
opacity: 0.8;
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
.theme-dark .footer {
|
| 358 |
+
border-top-color: rgba(255,255,255,0.1);
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
/* ==================== CHARACTER COUNTER ==================== */
|
| 362 |
+
.char-counter {
|
| 363 |
+
text-align: right;
|
| 364 |
+
font-size: 0.85em;
|
| 365 |
+
margin-top: 5px;
|
| 366 |
+
font-weight: 500;
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
/* ==================== RESPONSIVE ==================== */
|
| 370 |
+
@media (max-width: 768px) {
|
| 371 |
+
.hero-title {
|
| 372 |
+
font-size: 1.8em;
|
| 373 |
}
|
| 374 |
+
|
| 375 |
+
.hero-subtitle {
|
| 376 |
+
font-size: 1em;
|
|
|
|
| 377 |
}
|
| 378 |
+
|
| 379 |
+
.stats-container {
|
| 380 |
+
gap: 20px;
|
|
|
|
| 381 |
}
|
| 382 |
+
|
| 383 |
+
.stat-number {
|
| 384 |
+
font-size: 1.5em;
|
| 385 |
}
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
/* ==================== FEEDBACK WIDGET ==================== */
|
| 389 |
+
.feedback-btn {
|
| 390 |
+
opacity: 0.6;
|
| 391 |
+
transition: all 0.2s ease;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
.feedback-btn:hover {
|
| 395 |
+
opacity: 1;
|
| 396 |
+
transform: scale(1.1);
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
/* ==================== ACCESSIBILITY ==================== */
|
| 400 |
+
*:focus-visible {
|
| 401 |
+
outline: 2px solid #667eea;
|
| 402 |
+
outline-offset: 2px;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
/* ==================== SMOOTH SCROLLING ==================== */
|
| 406 |
+
html {
|
| 407 |
+
scroll-behavior: smooth;
|
| 408 |
+
}
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
# Enhanced JavaScript for theme detection and keyboard shortcuts
|
| 412 |
+
custom_js = """
|
| 413 |
+
function() {
|
| 414 |
+
// ==================== THEME DETECTION ====================
|
| 415 |
+
function updateTheme() {
|
| 416 |
+
const gradioApp = document.querySelector('gradio-app');
|
| 417 |
+
const body = document.body;
|
| 418 |
+
const html = document.documentElement;
|
| 419 |
+
|
| 420 |
+
const isDark = body.classList.contains('dark') ||
|
| 421 |
+
html.classList.contains('dark') ||
|
| 422 |
+
gradioApp?.classList.contains('dark') ||
|
| 423 |
+
window.matchMedia('(prefers-color-scheme: dark)').matches;
|
| 424 |
+
|
| 425 |
+
if (isDark) {
|
| 426 |
+
body.classList.add('theme-dark');
|
| 427 |
+
body.classList.remove('theme-light');
|
| 428 |
+
} else {
|
| 429 |
+
body.classList.add('theme-light');
|
| 430 |
+
body.classList.remove('theme-dark');
|
| 431 |
+
}
|
| 432 |
}
|
| 433 |
+
|
| 434 |
+
// Update theme immediately
|
| 435 |
+
updateTheme();
|
| 436 |
+
|
| 437 |
+
// Watch for theme changes
|
| 438 |
+
const observer = new MutationObserver(updateTheme);
|
| 439 |
+
observer.observe(document.documentElement, {
|
| 440 |
+
attributes: true,
|
| 441 |
+
attributeFilter: ['class', 'data-theme']
|
| 442 |
+
});
|
| 443 |
+
observer.observe(document.body, {
|
| 444 |
+
attributes: true,
|
| 445 |
+
attributeFilter: ['class', 'data-theme']
|
| 446 |
+
});
|
| 447 |
+
|
| 448 |
+
// Watch gradio-app
|
| 449 |
+
const checkGradioApp = setInterval(() => {
|
| 450 |
+
const app = document.querySelector('gradio-app');
|
| 451 |
+
if (app) {
|
| 452 |
+
observer.observe(app, {
|
| 453 |
+
attributes: true,
|
| 454 |
+
attributeFilter: ['class', 'data-theme']
|
| 455 |
+
});
|
| 456 |
+
clearInterval(checkGradioApp);
|
| 457 |
}
|
| 458 |
+
}, 100);
|
| 459 |
+
|
| 460 |
+
// Listen for system theme changes
|
| 461 |
+
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateTheme);
|
| 462 |
+
|
| 463 |
+
// ==================== KEYBOARD SHORTCUTS ====================
|
| 464 |
+
document.addEventListener('keydown', function(e) {
|
| 465 |
+
// Ctrl/Cmd + Enter to submit
|
| 466 |
+
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
|
| 467 |
+
const submitBtn = document.querySelector('button.primary-btn');
|
| 468 |
+
if (submitBtn) submitBtn.click();
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
// Escape to clear
|
| 472 |
+
if (e.key === 'Escape') {
|
| 473 |
+
const clearBtn = document.querySelector('[value="Clear"]');
|
| 474 |
+
if (clearBtn) clearBtn.click();
|
| 475 |
+
}
|
| 476 |
+
});
|
| 477 |
+
|
| 478 |
+
// ==================== SMOOTH ANIMATIONS ====================
|
| 479 |
+
// Add entrance animations
|
| 480 |
+
setTimeout(() => {
|
| 481 |
+
document.querySelectorAll('.gradio-container > *').forEach((el, idx) => {
|
| 482 |
+
el.style.opacity = '0';
|
| 483 |
+
el.style.transform = 'translateY(20px)';
|
| 484 |
+
setTimeout(() => {
|
| 485 |
+
el.style.transition = 'all 0.5s ease';
|
| 486 |
+
el.style.opacity = '1';
|
| 487 |
+
el.style.transform = 'translateY(0)';
|
| 488 |
+
}, idx * 50);
|
| 489 |
});
|
| 490 |
+
}, 100);
|
| 491 |
+
|
| 492 |
+
console.log('๐ง AI Concept Explainer v""" + VERSION + """loaded successfully!');
|
| 493 |
+
console.log('๐ก Keyboard shortcuts: Ctrl/Cmd+Enter to submit, Escape to clear');
|
| 494 |
+
}
|
| 495 |
+
"""
|
| 496 |
+
|
| 497 |
+
# ==================== BUILD GRADIO APP ====================
|
| 498 |
+
|
| 499 |
+
with gr.Blocks(
|
| 500 |
+
theme=gr.themes.Soft(
|
| 501 |
+
primary_hue="indigo",
|
| 502 |
+
secondary_hue="purple",
|
| 503 |
+
neutral_hue="slate",
|
| 504 |
+
font=[gr.themes.GoogleFont("Inter"), "Arial", "sans-serif"]
|
| 505 |
+
),
|
| 506 |
+
title=f"{APP_NAME} v{VERSION}",
|
| 507 |
+
css=custom_css,
|
| 508 |
+
js=custom_js
|
| 509 |
) as app:
|
| 510 |
+
|
| 511 |
+
# Hero Header
|
| 512 |
+
gr.HTML("""
|
| 513 |
+
<div class="hero-section">
|
| 514 |
+
<div class="hero-title">๐ง AI Concept Explainer</div>
|
| 515 |
+
<div class="hero-subtitle">Get clear, personalized explanations of any concept at your preferred complexity level and language</div>
|
| 516 |
+
</div>
|
| 517 |
""")
|
| 518 |
+
|
| 519 |
+
# Quick Examples
|
| 520 |
gr.Markdown("### ๐ก Quick Examples")
|
| 521 |
with gr.Row():
|
| 522 |
+
example_btn1 = gr.Button(EXAMPLE_QUESTIONS[0], size="sm", variant="secondary")
|
| 523 |
+
example_btn2 = gr.Button(EXAMPLE_QUESTIONS[1], size="sm", variant="secondary")
|
| 524 |
+
example_btn3 = gr.Button(EXAMPLE_QUESTIONS[2], size="sm", variant="secondary")
|
| 525 |
+
|
| 526 |
+
# Input Section
|
| 527 |
with gr.Row():
|
| 528 |
+
with gr.Column(scale=3):
|
| 529 |
question = gr.Textbox(
|
| 530 |
+
label="๐ญ What would you like to understand?",
|
| 531 |
placeholder="Enter your question or select an example above...",
|
| 532 |
lines=2,
|
| 533 |
max_lines=4
|
| 534 |
)
|
| 535 |
+
char_count = gr.HTML("<div class='char-counter'>0/500</div>")
|
| 536 |
+
|
| 537 |
with gr.Column(scale=1):
|
| 538 |
level = gr.Slider(
|
| 539 |
+
1, 5,
|
| 540 |
+
value=3,
|
| 541 |
+
step=1,
|
| 542 |
label="๐ Complexity Level",
|
| 543 |
info="1 = Simple, 5 = Expert"
|
| 544 |
)
|
| 545 |
language = gr.Dropdown(
|
| 546 |
+
LANGUAGES,
|
| 547 |
+
value="English",
|
| 548 |
label="๐ Language",
|
| 549 |
info="Choose your preferred language"
|
| 550 |
)
|
| 551 |
+
|
| 552 |
+
# Action Buttons
|
| 553 |
+
with gr.Row():
|
| 554 |
+
explain_btn = gr.Button(
|
| 555 |
+
"๐ Explain Concept",
|
| 556 |
+
variant="primary",
|
| 557 |
+
size="lg",
|
| 558 |
+
elem_classes=["primary-btn"]
|
| 559 |
+
)
|
| 560 |
+
clear_btn = gr.Button(
|
| 561 |
+
"๐ Clear",
|
| 562 |
+
variant="secondary",
|
| 563 |
+
size="lg"
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# Output Section
|
| 567 |
+
gr.Markdown("### ๐ Explanation")
|
| 568 |
+
reading_time = gr.Markdown("")
|
| 569 |
+
|
| 570 |
output = gr.Markdown(
|
| 571 |
+
value="*Your explanation will appear here...*",
|
| 572 |
elem_classes=["explanation-box"]
|
| 573 |
)
|
| 574 |
+
|
| 575 |
+
# Action buttons for output
|
| 576 |
+
with gr.Row():
|
| 577 |
+
copy_btn = gr.Button("๐ Copy to Clipboard", size="sm")
|
| 578 |
+
feedback_positive = gr.Button("๐ Helpful", size="sm", elem_classes=["feedback-btn"])
|
| 579 |
+
feedback_negative = gr.Button("๐ Not Helpful", size="sm", elem_classes=["feedback-btn"])
|
| 580 |
+
|
| 581 |
+
feedback_msg = gr.Markdown("")
|
| 582 |
+
|
| 583 |
+
# Footer
|
| 584 |
+
gr.HTML(f"""
|
| 585 |
+
<div class="footer">
|
| 586 |
+
<strong>{APP_NAME}</strong> v{VERSION} โข Powered by OpenAI GPT-4 โข Built with Gradio โข Made with โค๏ธ for learning
|
| 587 |
+
</div>
|
| 588 |
+
""")
|
| 589 |
+
|
| 590 |
+
# ==================== EVENT HANDLERS ====================
|
| 591 |
+
|
| 592 |
+
# Character counter
|
| 593 |
+
question.change(
|
| 594 |
+
fn=update_char_count,
|
| 595 |
+
inputs=[question],
|
| 596 |
+
outputs=[char_count]
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
# Example buttons
|
| 600 |
example_btn1.click(lambda: EXAMPLE_QUESTIONS[0], outputs=question)
|
| 601 |
example_btn2.click(lambda: EXAMPLE_QUESTIONS[1], outputs=question)
|
| 602 |
example_btn3.click(lambda: EXAMPLE_QUESTIONS[2], outputs=question)
|
| 603 |
+
|
| 604 |
+
# Main explain button
|
| 605 |
explain_btn.click(
|
| 606 |
+
fn=explain_concept,
|
| 607 |
+
inputs=[question, level, language],
|
| 608 |
+
outputs=[output, reading_time]
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# Clear button
|
| 612 |
+
clear_btn.click(
|
| 613 |
+
fn=clear_inputs,
|
| 614 |
+
outputs=[question, level, language]
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
# Copy button (client-side)
|
| 618 |
+
copy_btn.click(
|
| 619 |
+
None,
|
| 620 |
+
inputs=[output],
|
| 621 |
+
outputs=[feedback_msg],
|
| 622 |
+
js="""
|
| 623 |
+
(output) => {
|
| 624 |
+
const text = output;
|
| 625 |
+
navigator.clipboard.writeText(text).then(() => {
|
| 626 |
+
return 'โ
Copied to clipboard!';
|
| 627 |
+
}).catch(() => {
|
| 628 |
+
return 'โ Failed to copy. Please try manually selecting the text.';
|
| 629 |
+
});
|
| 630 |
+
}
|
| 631 |
+
"""
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
# Feedback buttons
|
| 635 |
+
def record_feedback(feedback_type: str) -> str:
|
| 636 |
+
logger.info(f"User feedback: {feedback_type}")
|
| 637 |
+
return f"โ
Thanks for your feedback!"
|
| 638 |
+
|
| 639 |
+
feedback_positive.click(
|
| 640 |
+
fn=lambda: record_feedback("positive"),
|
| 641 |
+
outputs=[feedback_msg]
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
feedback_negative.click(
|
| 645 |
+
fn=lambda: record_feedback("negative"),
|
| 646 |
+
outputs=[feedback_msg]
|
| 647 |
)
|
| 648 |
|
| 649 |
+
# ==================== APP LAUNCH ====================
|
| 650 |
+
|
| 651 |
def signal_handler(signum, frame):
|
| 652 |
"""Handle graceful shutdown for local development."""
|
| 653 |
+
logger.info(f"Received signal {signum}, shutting down gracefully...")
|
| 654 |
exit(0)
|
| 655 |
|
| 656 |
if __name__ == "__main__":
|
| 657 |
is_space = os.getenv('SPACE_ID') is not None
|
| 658 |
+
|
| 659 |
if not is_space:
|
| 660 |
signal.signal(signal.SIGINT, signal_handler)
|
| 661 |
+
|
| 662 |
+
logger.info(f"๐ Starting {APP_NAME} v{VERSION}...")
|
| 663 |
+
logger.info(f"API Key configured: {'โ
Yes' if openai_api_key else 'โ No'}")
|
| 664 |
+
|
| 665 |
if is_space:
|
| 666 |
app.launch(
|
| 667 |
server_name="0.0.0.0",
|