Learn_AI / app.py
Sabir55's picture
Update app.py
9b77781 verified
import streamlit as st
from fpdf import FPDF
from datetime import datetime
from gtts import gTTS
import os
import re
# -------------------------------
# Page Setup
# -------------------------------
st.set_page_config(page_title="AI For Everyone", layout="wide")
os.makedirs("audio", exist_ok=True)
# -------------------------------
# Session State Setup
# -------------------------------
if "analytics" not in st.session_state:
st.session_state.analytics = {}
if "leaderboard" not in st.session_state:
st.session_state.leaderboard = {}
if "started" not in st.session_state:
st.session_state.started = False
# -------------------------------
# Helpers
# -------------------------------
def clean_filename(text):
return re.sub(r"[^\w\s-]", "", text).replace(" ", "_")
def remove_non_latin(text):
return text.encode("latin-1", "ignore").decode("latin-1")
# -------------------------------
# Certificate Generator
# -------------------------------
def create_certificate(user, topic, score):
pdf = FPDF(orientation="L", unit="mm", format="A4")
pdf.add_page()
# Header bar
pdf.set_fill_color(0, 102, 204)
pdf.rect(0, 0, 297, 20, 'F')
pdf.set_text_color(255, 255, 255)
pdf.set_font("Arial", "B", 22)
pdf.set_y(5)
pdf.cell(0, 10, remove_non_latin("FUTURE TECH LEADERS"), ln=True, align="C")
# Main content
pdf.set_y(35)
pdf.set_text_color(0, 0, 0)
pdf.set_font("Arial", "B", 28)
pdf.cell(0, 15, remove_non_latin(user.upper()), ln=True, align="C")
pdf.set_font("Arial", "", 16)
pdf.cell(0, 10, remove_non_latin(f"has completed the training in {topic.upper()} under"), ln=True, align="C")
pdf.cell(0, 10, remove_non_latin("AI For Everyone - Digital Literacy Hub"), ln=True, align="C")
pdf.set_font("Arial", "I", 12)
pdf.cell(0, 10, remove_non_latin("Batch-01 | Jul 2025 - Sep 2025"), ln=True, align="C")
pdf.set_font("Arial", "", 14)
pdf.ln(4)
pdf.cell(0, 10, remove_non_latin(f"Score Achieved: {score}/5"), ln=True, align="C")
# Footer
pdf.set_y(-35)
pdf.set_font("Arial", "I", 11)
pdf.cell(0, 10, f"Issue Date: {datetime.today().strftime('%d/%m/%Y')}", ln=True, align="C")
pdf.cell(0, 10, remove_non_latin("Issued by Future Tech Leaders"), ln=True, align="C")
cert_id = f"FTL-{datetime.now().strftime('%y%m%d%H%M%S')}"
pdf.cell(0, 10, f"Certificate ID: {cert_id}", ln=True, align="C")
filename = f"{clean_filename(user)}_{clean_filename(topic)}.pdf"
pdf.output(filename)
return filename
# -------------------------------
# Audio Generator
# -------------------------------
def generate_audio_if_missing(topic, text):
filename = f"audio/{clean_filename(topic)}.mp3"
if not os.path.exists(filename):
tts = gTTS(text)
tts.save(filename)
return filename
# -------------------------------
# Topic Modules (Paste Full Here)
# -------------------------------
modules = {
"What is AI?": {
"intro": [
"Artificial Intelligence (AI) is the field of computer science that aims to create machines capable of intelligent behavior.",
"It involves building systems that can learn from data, reason through logic, perceive their environment, and make decisions.",
"AI is used in everyday applications like voice assistants, image recognition, and recommendation engines.",
"It draws on statistics, data mining, and machine learning algorithms.",
"AI can help automate repetitive tasks, saving time and reducing human error.",
"It powers self-driving cars, fraud detection systems, and smart healthcare tools.",
"There are different levelsβ€”such as narrow AI (task-specific) and general AI (multi-purpose).",
"Narrow AI is what we have today; general AI remains a future goal.",
"Understanding AI helps individuals adapt to the changing job market.",
"Ethical AI usage ensures fairness, transparency, and privacy.",
"Learning AI foundations enables you to innovate in various industries.",
"As data becomes central to modern life, AI skills become more essential."
],
"quiz": [
{"q": "AI stands for?", "O": ["Automated Interface","Artificial Intelligence","Applied Informatics","Advanced Integration"], "A": "Artificial Intelligence"},
{"q": "Narrow AI refers to systems that are?", "O": ["Task-specific","Human-like","Self-aware","Multilingual"], "A": "Task-specific"},
{"q": "Which powers voice assistants?", "O": ["AI","Manual Input","Open Source","Wireless"], "A": "AI"},
{"q": "General AI means?", "O": ["One task only","Human-level intelligence","Collecting data","Math only"], "A": "Human-level intelligence"},
{"q": "AI systems learn from?", "O": ["Data","Magic","Sunlight","Noise"], "A": "Data"}
]
},
"How ChatGPT Works": {
"intro": [
"ChatGPT is a language model built by OpenAI using deep learning techniques.",
"It was trained on a large dataset that includes books, articles, and websites.",
"It uses a transformer neural network architecture to predict the next word in a sentence.",
"By learning patterns of language, ChatGPT can generate fluent and coherent responses.",
"It can answer questions, write essays, help with code, and even generate creative content.",
"However, it does not truly understand meaningβ€”it relies on statistical patterns.",
"ChatGPT works best when prompts are specific and clear.",
"It's important to verify its output, especially for critical information.",
"Developers can use API endpoints to integrate ChatGPT into other tools.",
"AI creativity is impressiveβ€”but it may hallucinate if incorrectly prompted.",
"Ethical guidelines inform its usage: no hate speech, personal data misuse, or harmful content.",
"Understanding ChatGPT helps learners leverage AI responsibly."
],
"quiz": [
{"q": "ChatGPT is built by?", "O": ["Google","Meta","OpenAI","Amazon"], "A": "OpenAI"},
{"q": "It uses which neural net?", "O": ["CNN","RNN","Transformer","KNN"], "A": "Transformer"},
{"q": "ChatGPT generates text by predicting?", "O": ["Next word","Image pixels","Sound frequency","Encryption keys"], "A": "Next word"},
{"q": "Model trained on?", "O": ["Videos","Text data","Audio only","No data"], "A": "Text data"},
{"q": "Always verify its?", "O": ["Cooking skills","Factual output","Voice tone","Font size"], "A": "Factual output"}
]
},
"Types of AI": {
"intro": [
"AI can be categorized into Narrow AI, General AI, and Super AI.",
"Narrow AI performs specific tasks like translation or gameplay.",
"General AI would have human-like intelligence across domains - it's still a goal.",
"Super AI would surpass human intelligence in every aspect - purely theoretical today.",
"Narrow AI is abundant: speech recognition, spam filters, recommendation engines.",
"General and Super AI are topics of research and science fiction.",
"Ethical safeguards are crucial as AI capabilities grow.",
"Understanding AI categories helps set realistic expectations.",
"Today’s AI is powerful but limited by design.",
"Progress toward general AI involves integrating reasoning, planning, and learning."
],
"quiz": [
{"q": "Narrow AI does?", "O": ["Everything","One task","No tasks","Future tasks"], "A": "One task"},
{"q": "General AI equals?", "O": ["Calc machine","Human-like intelligence","Traffic light","Login system"], "A": "Human-like intelligence"},
{"q": "Super AI is?", "O": ["Here now","Future concept","Manual machine","Simple code"], "A": "Future concept"},
{"q": "Translation apps use?", "O": ["Narrow AI","Super AI","No AI","Magic"], "A": "Narrow AI"},
{"q": "Spam filters are?", "O": ["General AI","Narrow AI","No AI","Super AI"], "A": "Narrow AI"}
]
},
"AI in Daily Life": {
"intro": [
"AI is present in our daily routines: face unlock, recommendations, search.",
"Streaming platforms use AI to recommend songs and videos.",
"Navigation apps use AI to optimize routes and avoid traffic.",
"Banks use AI to detect fraud and assess loan risks.",
"E-commerce uses AI to show personalized product suggestions.",
"Smart homes use AI for voice control, thermostats, and lighting.",
"Healthcare uses AI to aid in diagnosis and personalized treatments.",
"Language translation apps use AI for real-time communication.",
"Smart agriculture uses AI for irrigation, yield prediction, and pest control.",
"Understanding these everyday uses helps appreciate AI’s impact."
],
"quiz": [
{"q": "Face unlock uses?", "O": ["AI","Password","QR code","Manual"], "A": "AI"},
{"q": "YouTube suggests videos based on?", "O": ["AI","Manual","Coin Toss","Ads"], "A": "AI"},
{"q": "Navigation apps predict?", "O": ["Weather only","Traffic patterns","Random","Lyrics"], "A": "Traffic patterns"},
{"q": "Banks use AI for?", "O": ["Fraud detection","Cooking","Car wash","Gaming"], "A": "Fraud detection"},
{"q": "Smart homes can?", "O": ["AI control","Time travel","Teleportation","None"], "A": "AI control"}
]
},
"ML vs DL": {
"intro": [
"Machine Learning (ML) is a subset of AI focused on learning from data.",
"Deep Learning (DL) is a specialized ML method using neural networks with multiple layers.",
"ML algorithms include linear regression, decision trees, SVM.",
"DL uses neural network architectures like CNNs and RNNs.",
"DL is powerful for images, voice, and unstructured data.",
"ML works well for smaller datasets and structured data.",
"DL needs large datasets and computational resources.",
"ML models are easier to interpret; DL models are often opaque.",
"Use case guides choice: ML for tabular data, DL for media recognition.",
"Knowing this helps choose the right approach for a project."
],
"quiz": [
{"q": "ML learns from?", "O": ["Data only","Magic","Nothing","Sunlight"], "A": "Data only"},
{"q": "DL uses?", "O": ["Neural networks","Manual rules","Static code","Papers"], "A": "Neural networks"},
{"q": "DL works best with?", "O": ["Lots of data","Little data","No data","Water"], "A": "Lots of data"},
{"q": "ML models are?", "O": ["Interpretable","Invisible","Random","Imaginary"], "A": "Interpretable"},
{"q": "Image recognition uses?", "O": ["DL","ML only","No AI","Analog"], "A": "DL"}
]
},
"Deepfakes & Misinformation": {
"intro": [
"Deepfakes are synthetic media created using AI.",
"They can manipulate images, audio, and video to create false realities.",
"These can spread misinformation and harm reputation.",
"AI-generated fake content makes media trust more complex.",
"Verifying authenticity is critical in news and social platforms.",
"Deepfakes may target public figures or individuals.",
"Tools exist to help detect fakes, but technology evolves quickly.",
"Responsibly sharing media includes verifying before posting.",
"Public awareness is the best defense against deepfake misuse.",
"Learning this protects communities and democracy."
],
"quiz": [
{"q": "Deepfake means?", "O": ["Real video","Fake video","News article","Game"], "A": "Fake video"},
{"q": "They use?", "O": ["AI","Coin toss","Weather","Manual"], "A": "AI"},
{"q": "Effect of deepfakes?", "O": ["Trust erosion","Fun only","Health boost","Wealth"], "A": "Trust erosion"},
{"q": "To prevent fake news you?", "O": ["Verify source","Trust all","Ignore everything","Respect rumors"], "A": "Verify source"},
{"q": "Detection tools use?", "O": ["AI","Magic","Guess","No method"], "A": "AI"}
]
},
"Data Privacy Basics": {
"intro": [
"Data privacy is about keeping personal information safe.",
"Personal data includes names, photos, location, health records.",
"Many apps collect dataβ€”it's important to know which you allow.",
"Strong passwords and 2FA protect online accounts.",
"Data sharing can expose you to scams and identity theft.",
"Privacy settings in apps empower users to choose control.",
"GDPR and similar laws protect user data rights.",
"Awareness helps prevent misuse by bad actors.",
"Encrypted communication like HTTPS secures your data.",
"Smart data handling builds trust and safety online."
],
"quiz": [
{"q": "Privacy protects?", "O": ["Personal info","Weather","Rivers","Animals"], "A": "Personal info"},
{"q": "2FA means?", "O": ["Double Factor Authentication","2 Forms Access","Two Fun Activities","None"], "A": "Double Factor Authentication"},
{"q": "Encrypted sites use?", "O": ["HTTPS","HTTP","FTP","POP3"], "A": "HTTPS"},
{"q": "Avoid sharing?", "O": ["Passwords","Jokes","Memes","Songs"], "A": "Passwords"},
{"q": "Privacy laws include?", "O": ["GDPR","HTML","NoSQL","CSS"], "A": "GDPR"}
]
},
"Ethics in AI": {
"intro": [
"AI ethics is about responsible, fair, and transparent AI usage.",
"Biased data can lead to unfair decisions in AI systems.",
"Ethical AI respects privacy and avoids discrimination.",
"Transparency means understanding how AI reaches decisions.",
"Regulations guide developers to use AI responsibly.",
"We must balance innovation with societal well-being.",
"Involving users in decisions builds trust in AI systems.",
"Ethical design empowers all stakeholders equally.",
"Learning AI ethics creates safer and fairer technologies.",
"Your knowledge can ensure AI benefits everyone."
],
"quiz": [
{"q": "AI ethics ensures?", "O": ["Fairness","Speed","Cost","None"], "A": "Fairness"},
{"q": "Biased AI can?", "O": ["Discriminate","Cook","Paint","Drive"], "A": "Discriminate"},
{"q": "Transparency means?", "O": ["Explain decisions","Hide code","Blur data","Remove users"], "A": "Explain decisions"},
{"q": "Ethical AI respects?", "O": ["Privacy","Speed","Noise","Weight"], "A": "Privacy"},
{"q": "Ethical design builds?", "O": ["Trust","Fear","Spam","Ads"], "A": "Trust"}
]
},
"Computer Vision & CV": {
"intro": [
"Computer Vision (CV) enables machines to interpret visual data.",
"It uses cameras, sensors, and algorithms to process images.",
"CV applications include facial recognition, object tracking, and medical imaging.",
"It uses CNNs, image filters, and feature extraction techniques.",
"CV helps quality inspection in factories and autonomous vehicles.",
"It can read handwritten text and diagnose diseases from scans.",
"Real-time video analysis helps surveillance and safety.",
"CV combined with AI enables powerful automation solutions.",
"Understanding CV opens doors to robotics and intelligent systems.",
"Ethical CV requires consent and data protection in public spaces."
],
"quiz": [
{"q": "CV stands for?", "O": ["Core Vision","Computer Vision","Camera View","Control Voice"], "A": "Computer Vision"},
{"q": "CV uses?", "O": ["Images","Audio","Text only","None"], "A": "Images"},
{"q": "CNN is used in?", "O": ["CV","Typing","Email","Games"], "A": "CV"},
{"q": "CV helps in factories by?", "O": ["Inspecting products","Cooking","Sleeping","Entertainment"], "A": "Inspecting products"},
{"q": "CV requires ?", "O": ["Privacy","Cameras","Coins","Walls"], "A": "Cameras"}
]
},
"AI in Healthcare": {
"intro": [
"AI improves healthcare by analyzing medical images for diagnosis.",
"It can detect anomalies in X-rays, MRIs and CT scans.",
"Predictive models help in identifying disease risks early.",
"AI-driven robots assist in surgeries with precision.",
"Chatbots help patients with common health queries.",
"Drug discovery processes are accelerated by AI algorithms.",
"Personalized care plans benefit from AI data analysis.",
"Hospital administration uses AI for scheduling and predictions.",
"Wearable AI devices monitor vitals and alert emergencies.",
"Ethical use ensures patient privacy and unbiased care."
],
"quiz": [
{"q": "AI in imaging helps detect?", "O": ["Diseases","Music","Movies","Weather"], "A": "Diseases"},
{"q": "Predictive AI finds?", "O": ["Risks early","New jokes","Songs","Photos"], "A": "Risks early"},
{"q": "Surgery robots are?", "O": ["AI-assisted","Manual only","Electric fans","Toys"], "A": "AI-assisted"},
{"q": "Chatbots in healthcare?", "O": ["Answer questions","Cook food","Dance","Sleep"], "A": "Answer questions"},
{"q": "Wearables monitor?", "O": ["Vitals","Sand","Stars","Cars"], "A": "Vitals"}
]
}
}
# Initialize analytics & leaderboard
for topic in modules:
st.session_state.analytics.setdefault(topic, 0)
st.session_state.leaderboard.setdefault(topic, [])
# -------------------------------
# Module Display
# -------------------------------
def show_module(topic):
explanation = "\n\n".join(modules[topic]["intro"])
audio_path = generate_audio_if_missing(topic, explanation)
st.audio(audio_path, format="audio/mp3")
st.markdown(explanation)
st.info("Answer the quiz:")
answers = []
for i, qd in enumerate(modules[topic]["quiz"]):
a = st.radio(f"Q{i+1}: {qd['q']}", qd['O'], index=None, key=f"{topic}_{i}")
answers.append(a)
name = st.text_input("Your full name (for certificate):", key=f"name_{topic}")
if st.button("Submit Quiz", key=f"btn_{topic}"):
if "" in answers or not name.strip():
st.warning("Please answer all questions and enter your name.")
return
score = sum(1 for ans, q in zip(answers, modules[topic]["quiz"]) if ans == q["A"])
st.success(f"You scored {score}/5")
st.balloons()
st.session_state.analytics[topic] += 1
st.session_state.leaderboard[topic].append({"name": name, "score": score})
st.session_state.leaderboard[topic] = sorted(
st.session_state.leaderboard[topic], key=lambda x: -x["score"]
)[:5]
cert = create_certificate(name, topic, score)
st.download_button("πŸ“„ Download Certificate", data=open(cert, "rb"), file_name=cert, mime="application/pdf")
share_text = f"I scored {score}/5 on '{topic}'! #AIForEveryone"
st.markdown(f"[πŸ”— WhatsApp](https://wa.me/?text={share_text}) | [🐦 Twitter](https://twitter.com/intent/tweet?text={share_text})")
st.subheader("βœ… Answer Key:")
for i, qd in enumerate(modules[topic]["quiz"]):
st.markdown(f"{i+1}. **{qd['q']}** β€” βœ… {qd['A']}")
# -------------------------------
# Start Screen
# -------------------------------
if not st.session_state.started:
st.title("πŸ€– AI For Everyone – Future Tech Leaders")
st.markdown("### Learn AI, earn certificates, and grow your future with the power of digital literacy.")
if st.button("πŸš€ Get Started Now"):
st.session_state.started = True
st.stop()
# -------------------------------
# Sidebar
# -------------------------------
st.sidebar.title("πŸ“˜ Topics")
topic = st.selectbox("Choose your module:", list(modules.keys()))
st.sidebar.subheader("πŸ“Š Completions")
for t, c in st.session_state.analytics.items():
st.sidebar.write(f"{t}: {c} completed")
st.sidebar.subheader("πŸ† Leaderboard")
for t, scores in st.session_state.leaderboard.items():
if scores:
st.sidebar.write(f"**{t}**")
for entry in scores:
st.sidebar.write(f"{entry['name']}: {entry['score']}/5")
# -------------------------------
# Main Content
# -------------------------------
show_module(topic)