Sabir55 commited on
Commit
68afc9e
·
verified ·
1 Parent(s): b85b061

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +277 -108
app.py CHANGED
@@ -6,155 +6,324 @@ import re
6
  # ------------------------------
7
  # Page Setup
8
  # ------------------------------
9
- st.set_page_config(page_title="AI For Everyone", layout="centered")
10
 
11
  # ------------------------------
12
- # Quiz Data
13
  # ------------------------------
14
- ai_modules = {
 
 
 
 
 
 
15
  "What is AI?": {
16
- "intro": "Artificial Intelligence (AI) means teaching machines to think, learn, and act like humans. AI can recognize images, understand voices, play games, and even help doctors.",
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  "quiz": [
18
- {"question": "What does AI stand for?", "options": ["Artificial Intelligence", "Automatic Internet", "Advanced Input", "Auto Instruction"], "answer": "Artificial Intelligence"},
19
- {"question": "Which is an example of AI?", "options": ["Fan", "Refrigerator", "Google Assistant", "Iron"], "answer": "Google Assistant"},
20
- {"question": "AI can help in which of these?", "options": ["Cooking", "Driving", "Sleeping", "None"], "answer": "Driving"},
21
- {"question": "What is NOT an AI skill?", "options": ["Talking", "Sleeping", "Recognizing faces", "Learning"], "answer": "Sleeping"},
22
- {"question": "AI is used in which app?", "options": ["YouTube", "Alarm Clock", "Torch", "Calendar"], "answer": "YouTube"},
23
  ]
24
  },
25
  "How ChatGPT Works": {
26
- "intro": "ChatGPT is a type of AI that understands your questions and gives smart answers using a large amount of text data it learned from books, websites, and more.",
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  "quiz": [
28
- {"question": "What is ChatGPT?", "options": ["Robot", "AI Chatbot", "Game", "Website"], "answer": "AI Chatbot"},
29
- {"question": "Who created ChatGPT?", "options": ["Google", "Meta", "OpenAI", "Amazon"], "answer": "OpenAI"},
30
- {"question": "ChatGPT learns from?", "options": ["Internet Data", "Photos", "TV Shows", "Music"], "answer": "Internet Data"},
31
- {"question": "What can ChatGPT NOT do?", "options": ["Talk to you", "Predict future", "Write articles", "Translate text"], "answer": "Predict future"},
32
- {"question": "ChatGPT gives answers based on?", "options": ["Magic", "Guess", "Trained data", "Surprise"], "answer": "Trained data"},
33
  ]
34
  },
35
  "Types of AI": {
36
- "intro": "There are three types of AI: Narrow AI (used in one task), General AI (like a human brain), and Super AI (stronger than humans – still in the future).",
 
 
 
 
 
 
 
 
 
 
 
37
  "quiz": [
38
- {"question": "Which AI is used in Siri or Alexa?", "options": ["Super AI", "General AI", "Narrow AI", "No AI"], "answer": "Narrow AI"},
39
- {"question": "Which AI doesn't exist yet?", "options": ["Narrow AI", "Super AI", "ChatGPT", "Machine Learning"], "answer": "Super AI"},
40
- {"question": "Which AI is as smart as humans?", "options": ["Super AI", "General AI", "Narrow AI", "Simple AI"], "answer": "General AI"},
41
- {"question": "ChatGPT is an example of?", "options": ["Super AI", "Narrow AI", "General AI", "Real Brain"], "answer": "Narrow AI"},
42
- {"question": "Which is used today in real life?", "options": ["General AI", "Super AI", "Narrow AI", "None"], "answer": "Narrow AI"},
43
  ]
44
  },
45
  "AI in Daily Life": {
46
- "intro": "AI helps us every day – in phones (face unlock), YouTube (video suggestions), hospitals (disease detection), farming (smart irrigation), and more.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  "quiz": [
48
- {"question": "AI is used in which app?", "options": ["Clock", "YouTube", "Flashlight", "Calculator"], "answer": "YouTube"},
49
- {"question": "Face unlock uses which tech?", "options": ["AI", "Password", "Fingerprint", "QR code"], "answer": "AI"},
50
- {"question": "AI helps doctors by?", "options": ["Playing music", "Writing books", "Detecting diseases", "Making beds"], "answer": "Detecting diseases"},
51
- {"question": "Which field uses AI for crops?", "options": ["Medicine", "Farming", "Sports", "Cooking"], "answer": "Farming"},
52
- {"question": "AI helps in?", "options": ["Sleeping", "Decision Making", "Singing", "Jumping"], "answer": "Decision Making"},
53
  ]
54
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  }
56
 
 
 
 
 
 
57
  # ------------------------------
58
- # Helper: Clean filename
59
  # ------------------------------
60
  def clean_filename(text):
61
- return re.sub(r'[^\w\s-]', '', text).replace(' ', '_')
62
 
63
- # ------------------------------
64
- # Certificate Generator
65
- # ------------------------------
66
- def generate_certificate(user_name: str, score: int, topic: str):
67
- pdf = FPDF(orientation='L', unit='mm', format='A4')
68
  pdf.add_page()
69
- pdf.set_font("Arial", 'B', 24)
70
- pdf.set_text_color(0, 102, 204)
71
- pdf.cell(0, 20, "Certificate of Completion", ln=True, align='C')
72
 
73
- pdf.set_text_color(0, 0, 0)
74
- pdf.set_font("Arial", '', 16)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  pdf.ln(10)
76
- pdf.cell(0, 10, f"This is to certify that", ln=True, align='C')
77
- pdf.set_font("Arial", 'B', 20)
78
- pdf.cell(0, 15, user_name, ln=True, align='C')
79
- pdf.set_font("Arial", '', 16)
80
- pdf.cell(0, 10, f"has successfully completed the quiz on", ln=True, align='C')
81
- pdf.set_font("Arial", 'B', 18)
82
- pdf.cell(0, 10, topic, ln=True, align='C')
83
- pdf.set_font("Arial", '', 16)
84
- pdf.cell(0, 10, f"with a score of {score}/5.", ln=True, align='C')
85
-
86
- pdf.set_font("Arial", 'I', 12)
87
- pdf.ln(20)
88
- pdf.cell(0, 10, f"Date: {datetime.today().strftime('%Y-%m-%d')}", ln=True, align='C')
89
- pdf.cell(0, 10, "Powered by BrainQuest AI", ln=True, align='C')
90
-
91
- safe_name = clean_filename(user_name)
92
- safe_topic = clean_filename(topic)
93
- filename = f"Certificate_{safe_name}_{safe_topic}.pdf"
94
  pdf.output(filename)
95
  return filename
96
 
97
  # ------------------------------
98
- # Quiz UI
99
  # ------------------------------
100
- def show_intro_and_quiz(topic):
101
- module = ai_modules[topic]
102
- st.markdown(f"### 📘 Topic: {topic}")
103
- st.info(module["intro"])
104
- st.markdown("#### 📝 Quiz Time")
105
-
106
- score = 0
107
- answers = {}
108
- for i, q in enumerate(module["quiz"]):
109
- selected = st.radio(f"**Q{i+1}: {q['question']}**", q['options'], index=None, key=f"{topic}_q{i}")
110
- answers[i] = selected
111
- if selected == q['answer']:
112
- score += 1
113
-
114
- user_name = st.text_input("Enter your full name for certificate:", key=f"name_{topic}")
115
-
116
- if st.button("✅ Submit Quiz", key=f"submit_{topic}"):
117
- if None in answers.values():
118
- st.warning("Please answer all questions before submitting.")
119
- elif not user_name.strip():
120
- st.warning("Please enter your name to get a certificate.")
121
- else:
122
- st.success(f"You scored {score} out of {len(module['quiz'])}!")
123
- st.balloons()
124
- cert_path = generate_certificate(user_name, score, topic)
125
- st.markdown("### 🎓 Download Your Certificate")
126
- st.download_button("📄 Download Certificate", data=open(cert_path, "rb"), file_name=cert_path, mime="application/pdf")
127
- for i, q in enumerate(module["quiz"]):
128
- st.markdown(f"**Q{i+1}: {q['question']}**")
129
- st.markdown(f"✅ Correct Answer: `{q['answer']}`")
130
- if answers[i] != q['answer']:
131
- st.markdown(f"❌ Your Answer: `{answers[i]}`")
132
- st.markdown("---")
133
 
134
  # ------------------------------
135
- # App Navigation
136
  # ------------------------------
137
  if "started" not in st.session_state:
138
  st.session_state.started = False
139
 
140
  if not st.session_state.started:
141
- st.markdown("""
142
- <div style='text-align:center;'>
143
- <h1 style='font-size:48px; color:#4CAF50;'>🤖 AI For Everyone</h1>
144
- <p style='font-size:22px;'>Learn AI in simple words. Built for everyone.</p>
145
- </div>
146
- """, unsafe_allow_html=True)
147
-
148
- if st.button("🚀 Get Started Now"):
149
  st.session_state.started = True
150
  st.stop()
151
 
152
- # Main Quiz Screen
153
- st.sidebar.title("📘 Topics")
154
- selected_topic = st.selectbox("Choose a topic to begin:", list(ai_modules.keys()))
155
-
156
- if selected_topic:
157
- show_intro_and_quiz(selected_topic)
158
 
159
- st.sidebar.markdown("---")
160
- st.sidebar.markdown("Built with ❤️ by **Sabir Ali**")
 
 
6
  # ------------------------------
7
  # Page Setup
8
  # ------------------------------
9
+ st.set_page_config(page_title="AI For Everyone", layout="wide")
10
 
11
  # ------------------------------
12
+ # Analytics persistence
13
  # ------------------------------
14
+ if "analytics" not in st.session_state:
15
+ st.session_state.analytics = {}
16
+
17
+ # ------------------------------
18
+ # Quiz Modules (10 topics)
19
+ # ------------------------------
20
+ modules = {
21
  "What is AI?": {
22
+ "intro": [
23
+ "Artificial Intelligence (AI) is the field of computer science that aims to create machines capable of intelligent behavior.",
24
+ "It involves building systems that can learn from data, reason through logic, perceive their environment, and make decisions.",
25
+ "AI is used in everyday applications like voice assistants, image recognition, and recommendation engines.",
26
+ "It draws on statistics, data mining, and machine learning algorithms.",
27
+ "AI can help automate repetitive tasks, saving time and reducing human error.",
28
+ "It powers self-driving cars, fraud detection systems, and smart healthcare tools.",
29
+ "There are different levels—such as narrow AI (task-specific) and general AI (multi-purpose).",
30
+ "Narrow AI is what we have today; general AI remains a future goal.",
31
+ "Understanding AI helps individuals adapt to the changing job market.",
32
+ "Ethical AI usage ensures fairness, transparency, and privacy.",
33
+ "Learning AI foundations enables you to innovate in various industries.",
34
+ "As data becomes central to modern life, AI skills become more essential."
35
+ ],
36
  "quiz": [
37
+ {"q": "AI stands for?", "O": ["Automated Interface","Artificial Intelligence","Applied Informatics","Advanced Integration"], "A": "Artificial Intelligence"},
38
+ {"q": "Narrow AI refers to systems that are?", "O": ["Task-specific","Human-like","Self-aware","Multilingual"], "A": "Task-specific"},
39
+ {"q": "Which powers voice assistants?", "O": ["AI","Manual Input","Open Source","Wireless"], "A": "AI"},
40
+ {"q": "General AI means?", "O": ["One task only","Human-level intelligence","Collecting data","Math only"], "A": "Human-level intelligence"},
41
+ {"q": "AI systems learn from?", "O": ["Data","Magic","Sunlight","Noise"], "A": "Data"}
42
  ]
43
  },
44
  "How ChatGPT Works": {
45
+ "intro": [
46
+ "ChatGPT is a language model built by OpenAI using deep learning techniques.",
47
+ "It was trained on a large dataset that includes books, articles, and websites.",
48
+ "It uses a transformer neural network architecture to predict the next word in a sentence.",
49
+ "By learning patterns of language, ChatGPT can generate fluent and coherent responses.",
50
+ "It can answer questions, write essays, help with code, and even generate creative content.",
51
+ "However, it does not truly understand meaning—it relies on statistical patterns.",
52
+ "ChatGPT works best when prompts are specific and clear.",
53
+ "It's important to verify its output, especially for critical information.",
54
+ "Developers can use API endpoints to integrate ChatGPT into other tools.",
55
+ "AI creativity is impressive—but it may hallucinate if incorrectly prompted.",
56
+ "Ethical guidelines inform its usage: no hate speech, personal data misuse, or harmful content.",
57
+ "Understanding ChatGPT helps learners leverage AI responsibly."
58
+ ],
59
  "quiz": [
60
+ {"q": "ChatGPT is built by?", "O": ["Google","Meta","OpenAI","Amazon"], "A": "OpenAI"},
61
+ {"q": "It uses which neural net?", "O": ["CNN","RNN","Transformer","KNN"], "A": "Transformer"},
62
+ {"q": "ChatGPT generates text by predicting?", "O": ["Next word","Image pixels","Sound frequency","Encryption keys"], "A": "Next word"},
63
+ {"q": "Model trained on?", "O": ["Videos","Text data","Audio only","No data"], "A": "Text data"},
64
+ {"q": "Always verify its?", "O": ["Cooking skills","Factual output","Voice tone","Font size"], "A": "Factual output"}
65
  ]
66
  },
67
  "Types of AI": {
68
+ "intro": [
69
+ "AI can be categorized into Narrow AI, General AI, and Super AI.",
70
+ "Narrow AI performs specific tasks like translation or gameplay.",
71
+ "General AI would have human-like intelligence across domains - it's still a goal.",
72
+ "Super AI would surpass human intelligence in every aspect - purely theoretical today.",
73
+ "Narrow AI is abundant: speech recognition, spam filters, recommendation engines.",
74
+ "General and Super AI are topics of research and science fiction.",
75
+ "Ethical safeguards are crucial as AI capabilities grow.",
76
+ "Understanding AI categories helps set realistic expectations.",
77
+ "Today’s AI is powerful but limited by design.",
78
+ "Progress toward general AI involves integrating reasoning, planning, and learning."
79
+ ],
80
  "quiz": [
81
+ {"q": "Narrow AI does?", "O": ["Everything","One task","No tasks","Future tasks"], "A": "One task"},
82
+ {"q": "General AI equals?", "O": ["Calc machine","Human-like intelligence","Traffic light","Login system"], "A": "Human-like intelligence"},
83
+ {"q": "Super AI is?", "O": ["Here now","Future concept","Manual machine","Simple code"], "A": "Future concept"},
84
+ {"q": "Translation apps use?", "O": ["Narrow AI","Super AI","No AI","Magic"], "A": "Narrow AI"},
85
+ {"q": "Spam filters are?", "O": ["General AI","Narrow AI","No AI","Super AI"], "A": "Narrow AI"}
86
  ]
87
  },
88
  "AI in Daily Life": {
89
+ "intro": [
90
+ "AI is present in our daily routines: face unlock, recommendations, search.",
91
+ "Streaming platforms use AI to recommend songs and videos.",
92
+ "Navigation apps use AI to optimize routes and avoid traffic.",
93
+ "Banks use AI to detect fraud and assess loan risks.",
94
+ "E-commerce uses AI to show personalized product suggestions.",
95
+ "Smart homes use AI for voice control, thermostats, and lighting.",
96
+ "Healthcare uses AI to aid in diagnosis and personalized treatments.",
97
+ "Language translation apps use AI for real-time communication.",
98
+ "Smart agriculture uses AI for irrigation, yield prediction, and pest control.",
99
+ "Understanding these everyday uses helps appreciate AI’s impact."
100
+ ],
101
+ "quiz": [
102
+ {"q": "Face unlock uses?", "O": ["AI","Password","QR code","Manual"], "A": "AI"},
103
+ {"q": "YouTube suggests videos based on?", "O": ["AI","Manual","Coin Toss","Ads"], "A": "AI"},
104
+ {"q": "Navigation apps predict?", "O": ["Weather only","Traffic patterns","Random","Lyrics"], "A": "Traffic patterns"},
105
+ {"q": "Banks use AI for?", "O": ["Fraud detection","Cooking","Car wash","Gaming"], "A": "Fraud detection"},
106
+ {"q": "Smart homes can?", "O": ["AI control","Time travel","Teleportation","None"], "A": "AI control"}
107
+ ]
108
+ },
109
+ "ML vs DL": {
110
+ "intro": [
111
+ "Machine Learning (ML) is a subset of AI focused on learning from data.",
112
+ "Deep Learning (DL) is a specialized ML method using neural networks with multiple layers.",
113
+ "ML algorithms include linear regression, decision trees, SVM.",
114
+ "DL uses neural network architectures like CNNs and RNNs.",
115
+ "DL is powerful for images, voice, and unstructured data.",
116
+ "ML works well for smaller datasets and structured data.",
117
+ "DL needs large datasets and computational resources.",
118
+ "ML models are easier to interpret; DL models are often opaque.",
119
+ "Use case guides choice: ML for tabular data, DL for media recognition.",
120
+ "Knowing this helps choose the right approach for a project."
121
+ ],
122
+ "quiz": [
123
+ {"q": "ML learns from?", "O": ["Data only","Magic","Nothing","Sunlight"], "A": "Data only"},
124
+ {"q": "DL uses?", "O": ["Neural networks","Manual rules","Static code","Papers"], "A": "Neural networks"},
125
+ {"q": "DL works best with?", "O": ["Lots of data","Little data","No data","Water"], "A": "Lots of data"},
126
+ {"q": "ML models are?", "O": ["Interpretable","Invisible","Random","Imaginary"], "A": "Interpretable"},
127
+ {"q": "Image recognition uses?", "O": ["DL","ML only","No AI","Analog"], "A": "DL"}
128
+ ]
129
+ },
130
+ "Deepfakes & Misinformation": {
131
+ "intro": [
132
+ "Deepfakes are synthetic media created using AI.",
133
+ "They can manipulate images, audio, and video to create false realities.",
134
+ "These can spread misinformation and harm reputation.",
135
+ "AI-generated fake content makes media trust more complex.",
136
+ "Verifying authenticity is critical in news and social platforms.",
137
+ "Deepfakes may target public figures or individuals.",
138
+ "Tools exist to help detect fakes, but technology evolves quickly.",
139
+ "Responsibly sharing media includes verifying before posting.",
140
+ "Public awareness is the best defense against deepfake misuse.",
141
+ "Learning this protects communities and democracy."
142
+ ],
143
+ "quiz": [
144
+ {"q": "Deepfake means?", "O": ["Real video","Fake video","News article","Game"], "A": "Fake video"},
145
+ {"q": "They use?", "O": ["AI","Coin toss","Weather","Manual"], "A": "AI"},
146
+ {"q": "Effect of deepfakes?", "O": ["Trust erosion","Fun only","Health boost","Wealth"], "A": "Trust erosion"},
147
+ {"q": "To prevent fake news you?", "O": ["Verify source","Trust all","Ignore everything","Respect rumors"], "A": "Verify source"},
148
+ {"q": "Detection tools use?", "O": ["AI","Magic","Guess","No method"], "A": "AI"}
149
+ ]
150
+ },
151
+ "Data Privacy Basics": {
152
+ "intro": [
153
+ "Data privacy is about keeping personal information safe.",
154
+ "Personal data includes names, photos, location, health records.",
155
+ "Many apps collect data—it's important to know which you allow.",
156
+ "Strong passwords and 2FA protect online accounts.",
157
+ "Data sharing can expose you to scams and identity theft.",
158
+ "Privacy settings in apps empower users to choose control.",
159
+ "GDPR and similar laws protect user data rights.",
160
+ "Awareness helps prevent misuse by bad actors.",
161
+ "Encrypted communication like HTTPS secures your data.",
162
+ "Smart data handling builds trust and safety online."
163
+ ],
164
  "quiz": [
165
+ {"q": "Privacy protects?", "O": ["Personal info","Weather","Rivers","Animals"], "A": "Personal info"},
166
+ {"q": "2FA means?", "O": ["Double Factor Authentication","2 Forms Access","Two Fun Activities","None"], "A": "Double Factor Authentication"},
167
+ {"q": "Encrypted sites use?", "O": ["HTTPS","HTTP","FTP","POP3"], "A": "HTTPS"},
168
+ {"q": "Avoid sharing?", "O": ["Passwords","Jokes","Memes","Songs"], "A": "Passwords"},
169
+ {"q": "Privacy laws include?", "O": ["GDPR","HTML","NoSQL","CSS"], "A": "GDPR"}
170
  ]
171
  },
172
+ "Ethics in AI": {
173
+ "intro": [
174
+ "AI ethics is about responsible, fair, and transparent AI usage.",
175
+ "Biased data can lead to unfair decisions in AI systems.",
176
+ "Ethical AI respects privacy and avoids discrimination.",
177
+ "Transparency means understanding how AI reaches decisions.",
178
+ "Regulations guide developers to use AI responsibly.",
179
+ "We must balance innovation with societal well-being.",
180
+ "Involving users in decisions builds trust in AI systems.",
181
+ "Ethical design empowers all stakeholders equally.",
182
+ "Learning AI ethics creates safer and fairer technologies.",
183
+ "Your knowledge can ensure AI benefits everyone."
184
+ ],
185
+ "quiz": [
186
+ {"q": "AI ethics ensures?", "O": ["Fairness","Speed","Cost","None"], "A": "Fairness"},
187
+ {"q": "Biased AI can?", "O": ["Discriminate","Cook","Paint","Drive"], "A": "Discriminate"},
188
+ {"q": "Transparency means?", "O": ["Explain decisions","Hide code","Blur data","Remove users"], "A": "Explain decisions"},
189
+ {"q": "Ethical AI respects?", "O": ["Privacy","Speed","Noise","Weight"], "A": "Privacy"},
190
+ {"q": "Ethical design builds?", "O": ["Trust","Fear","Spam","Ads"], "A": "Trust"}
191
+ ]
192
+ },
193
+ "Computer Vision & CV": {
194
+ "intro": [
195
+ "Computer Vision (CV) enables machines to interpret visual data.",
196
+ "It uses cameras, sensors, and algorithms to process images.",
197
+ "CV applications include facial recognition, object tracking, and medical imaging.",
198
+ "It uses CNNs, image filters, and feature extraction techniques.",
199
+ "CV helps quality inspection in factories and autonomous vehicles.",
200
+ "It can read handwritten text and diagnose diseases from scans.",
201
+ "Real-time video analysis helps surveillance and safety.",
202
+ "CV combined with AI enables powerful automation solutions.",
203
+ "Understanding CV opens doors to robotics and intelligent systems.",
204
+ "Ethical CV requires consent and data protection in public spaces."
205
+ ],
206
+ "quiz": [
207
+ {"q": "CV stands for?", "O": ["Core Vision","Computer Vision","Camera View","Control Voice"], "A": "Computer Vision"},
208
+ {"q": "CV uses?", "O": ["Images","Audio","Text only","None"], "A": "Images"},
209
+ {"q": "CNN is used in?", "O": ["CV","Typing","Email","Games"], "A": "CV"},
210
+ {"q": "CV helps in factories by?", "O": ["Inspecting products","Cooking","Sleeping","Entertainment"], "A": "Inspecting products"},
211
+ {"q": "CV requires ?", "O": ["Privacy","Cameras","Coins","Walls"], "A": "Cameras"}
212
+ ]
213
+ },
214
+ "AI in Healthcare": {
215
+ "intro": [
216
+ "AI improves healthcare by analyzing medical images for diagnosis.",
217
+ "It can detect anomalies in X-rays, MRIs and CT scans.",
218
+ "Predictive models help in identifying disease risks early.",
219
+ "AI-driven robots assist in surgeries with precision.",
220
+ "Chatbots help patients with common health queries.",
221
+ "Drug discovery processes are accelerated by AI algorithms.",
222
+ "Personalized care plans benefit from AI data analysis.",
223
+ "Hospital administration uses AI for scheduling and predictions.",
224
+ "Wearable AI devices monitor vitals and alert emergencies.",
225
+ "Ethical use ensures patient privacy and unbiased care."
226
+ ],
227
+ "quiz": [
228
+ {"q": "AI in imaging helps detect?", "O": ["Diseases","Music","Movies","Weather"], "A": "Diseases"},
229
+ {"q": "Predictive AI finds?", "O": ["Risks early","New jokes","Songs","Photos"], "A": "Risks early"},
230
+ {"q": "Surgery robots are?", "O": ["AI-assisted","Manual only","Electric fans","Toys"], "A": "AI-assisted"},
231
+ {"q": "Chatbots in healthcare?", "O": ["Answer questions","Cook food","Dance","Sleep"], "A": "Answer questions"},
232
+ {"q": "Wearables monitor?", "O": ["Vitals","Sand","Stars","Cars"], "A": "Vitals"}
233
+ ]
234
+ }
235
  }
236
 
237
+ # Initialize analytics
238
+ for topic in modules:
239
+ if topic not in st.session_state.analytics:
240
+ st.session_state.analytics[topic] = 0
241
+
242
  # ------------------------------
243
+ # Certificate Creation
244
  # ------------------------------
245
  def clean_filename(text):
246
+ return re.sub(r"[^\w\s-]", "", text).replace(" ", "_")
247
 
248
+ def create_certificate(user, topic, score):
249
+ pdf = FPDF(orientation="L", unit="mm", format="A4")
 
 
 
250
  pdf.add_page()
 
 
 
251
 
252
+ pdf.set_fill_color(0,102,204)
253
+ pdf.rect(0,0,297,30,'F')
254
+ pdf.set_font("Arial", "B", 28)
255
+ pdf.set_text_color(255,255,255)
256
+ pdf.cell(0,15,"Certificate of Mastery",ln=True,align="C")
257
+
258
+ pdf.set_fill_color(50,50,50)
259
+ pdf.rect(0,30,297,10,'F')
260
+ pdf.set_font("Arial","",16)
261
+ pdf.set_text_color(255,255,255)
262
+ pdf.cell(0,10,"Issued by Future Tech Leaders",ln=True,align="C")
263
+
264
+ pdf.ln(10)
265
+ pdf.set_text_color(0,0,0)
266
+ pdf.set_font("Arial","",14)
267
+ pdf.multi_cell(0,8,f"This certificate is proudly presented to {user} for successfully completing the module:",align="C")
268
+ pdf.ln(5)
269
+ pdf.set_font("Arial","B",20)
270
+ pdf.cell(0,10,topic,ln=True,align="C")
271
+ pdf.set_font("Arial","",14)
272
+ pdf.cell(0,10,f"with a score of {score}/5",ln=True,align="C")
273
  pdf.ln(10)
274
+ pdf.set_font("Arial","I",12)
275
+ pdf.cell(0,10,f"Date: {datetime.today().strftime('%Y-%m-%d')}",ln=True,align="C")
276
+
277
+ filename = f"{clean_filename(user)}_{clean_filename(topic)}.pdf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  pdf.output(filename)
279
  return filename
280
 
281
  # ------------------------------
282
+ # Module UI and Quiz
283
  # ------------------------------
284
+ def show_module(topic):
285
+ expl = "\n\n".join(modules[topic]["intro"])
286
+ st.write(expl)
287
+ st.info("Please answer the following questions:")
288
+
289
+ answers = []
290
+ for idx, qd in enumerate(modules[topic]["quiz"]):
291
+ ans = st.radio(f"Q{idx+1}: {qd['q']}", qd['O'], index=None, key=f"{topic}_{idx}")
292
+ answers.append(ans)
293
+
294
+ name = st.text_input("Enter your name for certificate:", key=f"name_{topic}")
295
+
296
+ if st.button("Submit Quiz", key=f"btn_{topic}"):
297
+ if "" in answers or not name.strip():
298
+ st.warning("Please answer all questions and enter your name.")
299
+ return
300
+ score = sum(1 for a,qd in zip(answers,modules[topic]["quiz"]) if a == qd["A"])
301
+ st.success(f"Your score: {score}/5")
302
+ st.session_state.analytics[topic] += 1
303
+ cert = create_certificate(name, topic, score)
304
+ st.download_button("Download Certificate", data=open(cert,"rb"), file_name=cert, mime="application/pdf")
305
+ st.subheader("Answer Key")
306
+ for i,qd in enumerate(modules[topic]["quiz"]):
307
+ st.markdown(f"{i+1}. **{qd['q']}** — ✅ {qd['A']}")
 
 
 
 
 
 
 
 
 
308
 
309
  # ------------------------------
310
+ # Navigation
311
  # ------------------------------
312
  if "started" not in st.session_state:
313
  st.session_state.started = False
314
 
315
  if not st.session_state.started:
316
+ st.title("AI For Everyone — Empowering Youth with Future Tech Leaders")
317
+ st.write("Choose a topic and start learning AI like never before!")
318
+ if st.button("Start Learning Now"):
 
 
 
 
 
319
  st.session_state.started = True
320
  st.stop()
321
 
322
+ # Sidebar Analytics
323
+ st.sidebar.header("📊 Quiz Completions")
324
+ for t, c in st.session_state.analytics.items():
325
+ st.sidebar.write(f"{t}: {c}")
 
 
326
 
327
+ # Main selection
328
+ topic = st.selectbox("Select a topic:", list(modules.keys()))
329
+ show_module(topic)