Spaces:
Running
Running
File size: 11,030 Bytes
bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 593b032 bc1ce79 d21d521 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# EDUTUTOR AI - Complete app.py for Hugging Face Spaces
# An intelligent AI tutor powered by IBM Granite that provides personalized educational explanations across multiple subjects and difficulty levels.
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
import warnings
warnings.filterwarnings("ignore")
class EduTutorAI:
def __init__(self):
self.model_name = "ibm-granite/granite-3.3-2b-instruct"
self.tokenizer = None
self.model = None
self.pipe = None
self.conversation_history = []
def load_model(self):
"""Load the Granite model and tokenizer"""
try:
print("Loading EDUTUTOR AI model...")
# Load tokenizer
self.tokenizer = AutoTokenizer.from_pretrained(
self.model_name,
trust_remote_code=True
)
# Load model with optimization for deployment
self.model = AutoModelForCausalLM.from_pretrained(
self.model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
low_cpu_mem_usage=True
)
# Create pipeline
self.pipe = pipeline(
"text-generation",
model=self.model,
tokenizer=self.tokenizer,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None
)
print("β
Model loaded successfully!")
return True
except Exception as e:
print(f"β Error loading model: {str(e)}")
return False
def create_educational_prompt(self, user_question, subject="General", difficulty="Intermediate"):
"""Create an educational prompt template"""
system_prompt = f"""You are EDUTUTOR AI, an expert educational tutor specializing in {subject}.
Your role is to:
1. Provide clear, accurate explanations at {difficulty} level
2. Break down complex concepts into digestible parts
3. Use examples and analogies when helpful
4. Encourage learning through questions
5. Be patient and supportive
Student Question: {user_question}
Please provide a comprehensive yet accessible explanation:"""
return system_prompt
def generate_response(self, question, subject, difficulty, max_length=512):
"""Generate educational response"""
if not self.pipe:
return "β Model not loaded. Please wait for initialization."
try:
# Create educational prompt
prompt = self.create_educational_prompt(question, subject, difficulty)
# Generate response
response = self.pipe(
prompt,
max_length=max_length,
num_return_sequences=1,
temperature=0.7,
do_sample=True,
pad_token_id=self.tokenizer.eos_token_id,
truncation=True
)
# Extract the generated text
full_response = response[0]['generated_text']
# Remove the prompt to get only the AI response
ai_response = full_response.replace(prompt, "").strip()
# Store in conversation history
self.conversation_history.append({
"question": question,
"subject": subject,
"difficulty": difficulty,
"response": ai_response
})
return ai_response
except Exception as e:
return f"β Error generating response: {str(e)}"
def get_conversation_history(self):
"""Get formatted conversation history"""
if not self.conversation_history:
return "No conversation history yet."
history = "π **EDUTUTOR AI - Learning Session History**\n\n"
for i, conv in enumerate(self.conversation_history[-5:], 1): # Show last 5 conversations
history += f"**Session {i}:**\n"
history += f"π― Subject: {conv['subject']} | Level: {conv['difficulty']}\n"
history += f"β Question: {conv['question']}\n"
history += f"π‘ Response: {conv['response'][:200]}...\n\n"
return history
def clear_history(self):
"""Clear conversation history"""
self.conversation_history = []
return "ποΈ Conversation history cleared!"
# Initialize the EduTutor AI
edututor = EduTutorAI()
# Load model function for Gradio
def initialize_model():
"""Initialize the model and return status"""
success = edututor.load_model()
if success:
return "β
EDUTUTOR AI is ready! You can now start asking questions."
else:
return "β Failed to load model. Please try again."
# Main chat function
def chat_with_edututor(question, subject, difficulty, max_length):
"""Main chat interface function"""
if not question.strip():
return "Please enter a question to get started!"
response = edututor.generate_response(question, subject, difficulty, max_length)
return response
# Create Gradio interface
def create_interface():
"""Create the EDUTUTOR AI Gradio interface"""
with gr.Blocks(
title="π EDUTUTOR AI - Your Personal Learning Assistant",
theme=gr.themes.Soft(),
css="""
.gradio-container {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.main-header {
text-align: center;
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
}
"""
) as interface:
# Header
gr.HTML("""
<div class="main-header">
<h1>π EDUTUTOR AI</h1>
<p>Your Intelligent Educational Tutor powered by IBM Granite 3.3-2B</p>
<p><em>Ask questions, learn concepts, and expand your knowledge!</em></p>
</div>
""")
# Model initialization section
with gr.Row():
with gr.Column():
init_button = gr.Button("π Initialize EDUTUTOR AI", variant="primary", size="lg")
init_status = gr.Textbox(
label="Initialization Status",
value="Click 'Initialize EDUTUTOR AI' to start",
interactive=False
)
# Main interface
with gr.Row():
with gr.Column(scale=2):
# Input section
with gr.Group():
gr.Markdown("### π Ask Your Question")
question_input = gr.Textbox(
label="Your Question",
placeholder="e.g., Explain quantum physics, How does photosynthesis work?, What is machine learning?",
lines=3
)
with gr.Row():
subject_dropdown = gr.Dropdown(
choices=[
"General", "Mathematics", "Physics", "Chemistry",
"Biology", "Computer Science", "History", "Literature",
"Geography", "Economics", "Philosophy"
],
value="General",
label="Subject Area"
)
difficulty_dropdown = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
value="Intermediate",
label="Difficulty Level"
)
max_length_slider = gr.Slider(
minimum=100,
maximum=1000,
value=512,
step=50,
label="Response Length (tokens)"
)
ask_button = gr.Button("π€ Ask EDUTUTOR AI", variant="primary")
with gr.Column(scale=1):
# Quick actions
with gr.Group():
gr.Markdown("### β‘ Quick Actions")
history_button = gr.Button("π View Learning History")
clear_button = gr.Button("ποΈ Clear History")
gr.Markdown("### π‘ Tips")
gr.Markdown("""
- Be specific with your questions
- Select appropriate subject and difficulty
- Use follow-up questions for deeper understanding
- Experiment with different difficulty levels
""")
# Response section
with gr.Row():
response_output = gr.Textbox(
label="π EDUTUTOR AI Response",
lines=15,
max_lines=20,
interactive=False
)
# History section
with gr.Row():
history_output = gr.Textbox(
label="π Learning Session History",
lines=10,
interactive=False,
visible=False
)
# Event handlers
init_button.click(
fn=initialize_model,
outputs=init_status
)
ask_button.click(
fn=chat_with_edututor,
inputs=[question_input, subject_dropdown, difficulty_dropdown, max_length_slider],
outputs=response_output
)
question_input.submit(
fn=chat_with_edututor,
inputs=[question_input, subject_dropdown, difficulty_dropdown, max_length_slider],
outputs=response_output
)
history_button.click(
fn=edututor.get_conversation_history,
outputs=history_output
).then(
fn=lambda: gr.update(visible=True),
outputs=history_output
)
clear_button.click(
fn=edututor.clear_history,
outputs=init_status
)
return interface
# Launch the application
if __name__ == "__main__":
print("π Starting EDUTUTOR AI...")
print("=" * 50)
# Create and launch interface
demo = create_interface()
# Launch for Hugging Face Spaces (simplified)
demo.launch()
|