StanKonkin commited on
Commit
f86d663
·
verified ·
1 Parent(s): 2f71d75

Uploading all the project files

Browse files
Files changed (3) hide show
  1. README.md +192 -6
  2. app.py +213 -0
  3. requirements.txt +9 -0
README.md CHANGED
@@ -1,14 +1,200 @@
1
  ---
2
  title: AI Concept Explainer
3
- emoji: 😻
4
- colorFrom: yellow
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 5.47.2
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: 'Explains concepts at different complexity and languages. '
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: AI Concept Explainer
3
+ emoji: 🧠
4
+ colorFrom: purple
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: "5.47.2"
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: AI-powered concept explainer
12
  ---
13
 
14
+ # 🧠 AI Concept Explainer
15
+
16
+ An intelligent Gradio app that explains any concept at different complexity levels using OpenAI's GPT models. Get personalized explanations tailored to your understanding level and preferred language.
17
+
18
+ ## 🎯 Features
19
+
20
+ - **Adaptive Complexity**: 5 levels from "like I'm 5" to expert-level explanations
21
+ - **Multi-language Support**: English, Russian, German, Spanish, French, Italian
22
+ - **Streaming Responses**: Real-time explanation generation
23
+ - **Quick Examples**: Pre-loaded sample questions for instant testing
24
+ - **Modern UI**: Clean, responsive interface with gradient styling
25
+ - **Error Handling**: Graceful API error management
26
+
27
+ ## 🚀 Quick Start
28
+
29
+ ### Prerequisites
30
+ - Python 3.7+
31
+ - OpenAI API key
32
+ - Gradio library
33
+
34
+ ### Installation & Setup
35
+
36
+ 1. **Navigate to the project directory**:
37
+ ```bash
38
+ cd gradio_concept_explainer
39
+ ```
40
+
41
+ 2. **Activate the virtual environment**:
42
+ ```bash
43
+ source ../adk_venv/bin/activate
44
+ ```
45
+
46
+ 3. **Install dependencies**:
47
+ ```bash
48
+ pip install gradio openai python-dotenv
49
+ ```
50
+
51
+ 4. **Set up your OpenAI API key**:
52
+ ```bash
53
+ # Create or edit api_keys.env file
54
+ echo "OPENAI_API_KEY=your_api_key_here" > ../api_keys.env
55
+ ```
56
+
57
+ 5. **Run the application**:
58
+ ```bash
59
+ python app.py
60
+ ```
61
+
62
+ 6. **Open your browser** and navigate to:
63
+ ```
64
+ http://127.0.0.1:7860
65
+ ```
66
+
67
+ ## 🎮 How to Use
68
+
69
+ 1. **Enter your question** in the text box or click a quick example
70
+ 2. **Select complexity level** (1-5) using the slider
71
+ 3. **Choose your language** from the dropdown
72
+ 4. **Click "Explain Concept"** to generate your personalized explanation
73
+
74
+ ### Complexity Levels
75
+ - **Level 1**: Like I'm 5 years old - simple words and analogies
76
+ - **Level 2**: Like I'm 10 years old - basic concepts with examples
77
+ - **Level 3**: High school level - intermediate with some technical terms
78
+ - **Level 4**: College level - advanced concepts with detailed explanations
79
+ - **Level 5**: Expert level - professional depth with technical precision
80
+
81
+ ## 📋 Example Questions
82
+
83
+ - "Why is the sky blue?"
84
+ - "How does the internet work?"
85
+ - "What is artificial intelligence?"
86
+ - "Explain quantum computing"
87
+ - "How do vaccines work?"
88
+
89
+ ## 🔧 Technical Details
90
+
91
+ ### Architecture
92
+ - **Framework**: Gradio 5.47.2
93
+ - **AI Model**: OpenAI GPT-4.1
94
+ - **Language**: Python 3.7+
95
+ - **Streaming**: Real-time response generation
96
+ - **Port**: localhost:7860
97
+
98
+ ### Key Functions
99
+
100
+ #### `explain_concept(question, level, language)`
101
+ Generates streaming explanations using OpenAI API.
102
+ - **Parameters**:
103
+ - `question` (str): Concept to explain
104
+ - `level` (int): Complexity level (1-5)
105
+ - `language` (str): Output language
106
+ - **Returns**: Streaming explanation chunks
107
+ - **Error Handling**: Graceful API error management
108
+
109
+ ### Environment Support
110
+ - **Local Development**: Auto-opens browser, localhost only
111
+ - **Hugging Face Spaces**: Production-ready configuration
112
+ - **Signal Handling**: Graceful shutdown for development
113
+
114
+ ## 🎨 Interface Design
115
+
116
+ - **Modern Theme**: Soft gradient styling
117
+ - **Responsive Layout**: Works on all screen sizes
118
+ - **Interactive Elements**: Sliders, dropdowns, example buttons
119
+ - **Real-time Streaming**: Live explanation generation
120
+ - **Accessible Design**: Clear labels and error messages
121
+
122
+ ## 🛠️ Customization
123
+
124
+ ### Adding New Languages
125
+ ```python
126
+ LANGUAGES = ["English", "Russian", "German", "Spanish", "French", "Italian", "YourLanguage"]
127
+ ```
128
+
129
+ ### Modifying Complexity Levels
130
+ ```python
131
+ EXPLANATION_LEVELS = {
132
+ 1: "your custom level 1 description",
133
+ 2: "your custom level 2 description",
134
+ # ... add more levels
135
+ }
136
+ ```
137
+
138
+ ### Changing the AI Model
139
+ ```python
140
+ stream = client.chat.completions.create(
141
+ model="gpt-3.5-turbo", # Change model here
142
+ # ... rest of parameters
143
+ )
144
+ ```
145
+
146
+ ## 🔒 Security & Privacy
147
+
148
+ - **API Key Protection**: Environment variable storage
149
+ - **Local Execution**: No data persistence
150
+ - **Secure Requests**: HTTPS API calls to OpenAI
151
+ - **No Data Storage**: Explanations not saved locally
152
+
153
+ ## 🚨 Troubleshooting
154
+
155
+ ### Common Issues
156
+
157
+ 1. **"OPENAI_API_KEY not found"**:
158
+ ```bash
159
+ # Set your API key in api_keys.env
160
+ echo "OPENAI_API_KEY=your_key_here" > ../api_keys.env
161
+ ```
162
+
163
+ 2. **"Module not found" errors**:
164
+ ```bash
165
+ pip install gradio openai python-dotenv
166
+ ```
167
+
168
+ 3. **Port already in use**:
169
+ ```python
170
+ # Change port in app.py
171
+ server_port=7861
172
+ ```
173
+
174
+ 4. **API rate limits**:
175
+ - Check your OpenAI usage limits
176
+ - Consider upgrading your OpenAI plan
177
+
178
+ ## 📈 Future Enhancements
179
+
180
+ - **Voice Output**: Text-to-speech for explanations
181
+ - **Visual Diagrams**: Generate concept illustrations
182
+ - **Explanation History**: Save and revisit past explanations
183
+ - **Custom Prompts**: User-defined explanation styles
184
+ - **Export Options**: Save explanations as PDF/Word
185
+ - **Collaborative Features**: Share explanations with others
186
+
187
+ ## 📝 License
188
+
189
+ This project is part of the LLM and Agentic AI Bootcamp Materials.
190
+
191
+ ## 👥 Contributing
192
+
193
+ This AI Concept Explainer is designed as a learning example. Feel free to:
194
+ - Fork and modify for personal use
195
+ - Use as a starting point for similar projects
196
+ - Suggest improvements or additional features
197
+
198
+ ---
199
+
200
+ **Get clear explanations for any concept! 🎯**
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI Concept Explainer
3
+ ===================
4
+
5
+ A Gradio app that explains concepts at different complexity levels
6
+ and in multiple languages using OpenAI's models.
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 - supports both local .env and Hugging Face Spaces
16
+ try:
17
+ load_dotenv('api_keys.env')
18
+ except:
19
+ pass # Gracefully handle missing .env file
20
+
21
+ # Initialize OpenAI client with API key validation
22
+ openai_api_key = os.getenv("OPENAI_API_KEY")
23
+ if not openai_api_key:
24
+ raise ValueError("OPENAI_API_KEY not found. Please set it in your environment variables or .env file.")
25
+
26
+ client = OpenAI(api_key=openai_api_key)
27
+
28
+ # Explanation complexity levels with clear descriptions
29
+ EXPLANATION_LEVELS = {
30
+ 1: "like I'm 5 years old - use simple words and analogies",
31
+ 2: "like I'm 10 years old - basic concepts with examples",
32
+ 3: "like a high school student - intermediate level with some technical terms",
33
+ 4: "like a college student - advanced concepts with detailed explanations",
34
+ 5: "like an expert in the field - professional level with technical depth",
35
+ }
36
+
37
+ # Supported languages for explanations
38
+ LANGUAGES = ["English", "Russian", "German", "Spanish", "French", "Italian"]
39
+
40
+ # Example questions for quick selection
41
+ EXAMPLE_QUESTIONS = [
42
+ "Why is the sky blue?",
43
+ "How does the internet work?",
44
+ "What is artificial intelligence?"
45
+ ]
46
+
47
+ def explain_concept(question, level, language):
48
+ """
49
+ Generate a comprehensive explanation for a given concept at the specified complexity level.
50
+ Supports streaming for real-time response generation.
51
+
52
+ Args:
53
+ question (str): The concept or question to explain
54
+ level (int): Complexity level (1-5)
55
+ language (str): Language for the explanation
56
+
57
+ Yields:
58
+ str: The generated explanation chunks or error message
59
+ """
60
+ # Input validation
61
+ if not question.strip():
62
+ yield "❌ Please enter a concept to explain."
63
+ return
64
+
65
+ # Get explanation level description
66
+ level_desc = EXPLANATION_LEVELS.get(level, "clearly and comprehensively")
67
+
68
+ # Language validation with fallback
69
+ if language not in LANGUAGES:
70
+ language = "English"
71
+
72
+ # Professional system prompt for focused explanations
73
+ system_prompt = f"""You are an expert educator. Explain the given concept {level_desc} in {language}. Provide a clear, accurate response in under 200 words. Ensure you use bold text to emphasize the key points. Do not include introductions, conclusions, or extra commentary - just the explanation."""
74
+
75
+ try:
76
+ # Generate streaming explanation using OpenAI API
77
+ stream = client.chat.completions.create(
78
+ model="gpt-4.1",
79
+ messages=[
80
+ {"role": "system", "content": system_prompt},
81
+ {"role": "user", "content": question}
82
+ ],
83
+ temperature=0.7,
84
+ max_tokens=1000,
85
+ stream=True # Enable streaming
86
+ )
87
+
88
+ # Proper word-by-word streaming with partial accumulation
89
+ partial = ""
90
+ for chunk in stream:
91
+ delta = getattr(chunk.choices[0].delta, "content", None)
92
+ if delta:
93
+ partial += delta
94
+ yield partial
95
+
96
+ except Exception as e:
97
+ yield f"❌ Error generating explanation: {str(e)}"
98
+
99
+ # Create enhanced Gradio interface with modern styling
100
+ with gr.Blocks(
101
+ theme=gr.themes.Soft(), # Modern, clean theme
102
+ title="AI Concept Explainer",
103
+ css="""
104
+ .gradio-container {
105
+ max-width: 900px !important;
106
+ margin: auto !important;
107
+ }
108
+ .explanation-box {
109
+ background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
110
+ color: #222;
111
+ padding: 20px;
112
+ border-radius: 10px;
113
+ margin: 10px 0;
114
+ }
115
+ """
116
+ ) as app:
117
+ # Header with description
118
+ gr.Markdown("""
119
+ # 🧠 AI Concept Explainer
120
+
121
+ Get clear, personalized explanations of any concept at your preferred complexity level and language.
122
+ """)
123
+
124
+ # Example selection section
125
+ gr.Markdown("### 💡 Quick Examples")
126
+ with gr.Row():
127
+ example_btn1 = gr.Button("Why is the sky blue?", size="sm", variant="secondary")
128
+ example_btn2 = gr.Button("How does the internet work?", size="sm", variant="secondary")
129
+ example_btn3 = gr.Button("What is artificial intelligence?", size="sm", variant="secondary")
130
+
131
+ # Input section with improved layout
132
+ with gr.Row():
133
+ with gr.Column(scale=2):
134
+ question = gr.Textbox(
135
+ label="💡 What would you like to understand?",
136
+ placeholder="Enter your question or select an example above...",
137
+ lines=2,
138
+ max_lines=4
139
+ )
140
+ with gr.Column(scale=1):
141
+ level = gr.Slider(
142
+ 1, 5,
143
+ value=3,
144
+ step=1,
145
+ label="📊 Complexity Level",
146
+ info="1 = Simple, 5 = Expert"
147
+ )
148
+ language = gr.Dropdown(
149
+ LANGUAGES,
150
+ value="English",
151
+ label="🌍 Language",
152
+ info="Choose your preferred language"
153
+ )
154
+
155
+ # Action button with enhanced styling
156
+ explain_btn = gr.Button(
157
+ "🚀 Explain Concept",
158
+ variant="primary",
159
+ size="lg"
160
+ )
161
+
162
+ # Output section with better formatting
163
+ output = gr.Markdown(
164
+ label="📝 Explanation",
165
+ elem_classes=["explanation-box"]
166
+ )
167
+
168
+ # Connect example buttons to populate question field
169
+ example_btn1.click(lambda: EXAMPLE_QUESTIONS[0], outputs=question)
170
+ example_btn2.click(lambda: EXAMPLE_QUESTIONS[1], outputs=question)
171
+ example_btn3.click(lambda: EXAMPLE_QUESTIONS[2], outputs=question)
172
+
173
+ # Connect button click to explanation function with streaming
174
+ explain_btn.click(
175
+ explain_concept,
176
+ inputs=[question, level, language],
177
+ outputs=output
178
+ )
179
+
180
+ def signal_handler(signum, frame):
181
+ """Handle graceful shutdown signals for local development."""
182
+ print(f"Received signal {signum}, shutting down gracefully...")
183
+ exit(0)
184
+
185
+ if __name__ == "__main__":
186
+ # Detect environment - Hugging Face Spaces vs local development
187
+ is_space = os.getenv('SPACE_ID') is not None
188
+
189
+ # Set up signal handler for local development only
190
+ if not is_space:
191
+ signal.signal(signal.SIGINT, signal_handler)
192
+
193
+ print("🚀 Starting AI Concept Explainer...")
194
+ print(f"Environment: {'Hugging Face Spaces' if is_space else 'Local Development'}")
195
+
196
+ if is_space:
197
+ # Production configuration for Hugging Face Spaces
198
+ app.launch(
199
+ server_name="0.0.0.0", # Accept external connections
200
+ server_port=7860, # Standard Spaces port
201
+ show_error=True, # Display errors in UI
202
+ quiet=False # Show startup logs
203
+ )
204
+ else:
205
+ # Development configuration for local use
206
+ app.launch(
207
+ share=False, # No public sharing
208
+ server_name="127.0.0.1", # Localhost only
209
+ server_port=7860, # Consistent port
210
+ inbrowser=True, # Auto-open browser
211
+ show_error=True, # Display errors in UI
212
+ quiet=False # Show startup logs
213
+ )
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Python 3.12.11
2
+ # Local versions:
3
+ # gradio==5.46.0
4
+ # openai==1.107.3
5
+ # python-dotenv==1.1.1
6
+
7
+ gradio
8
+ openai
9
+ python-dotenv