Spaces:
Sleeping
Sleeping
File size: 9,559 Bytes
f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae b356118 f4f55ae b356118 f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc f4f55ae d7c4abc e158050 f4f55ae b356118 f4f55ae b356118 f4f55ae b356118 f4f55ae e158050 b356118 f4f55ae e158050 f4f55ae b356118 e158050 | 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 |
import os
os.system('conda install -c conda-forge youtube-transcript-api -y')
import subprocess
subprocess.check_call(["pip", "install", "transformers==4.34.0"])
subprocess.check_call(["pip", "install", "torch>=1.7.1"])
subprocess.check_call(["pip", "install", "youtube_transcript_api>=0.6.3"])
subprocess.check_call(["pip", "install", "pytube"])
subprocess.check_call(["pip", "install", "huggingface_hub>=0.19.0"])
subprocess.check_call(["pip", "install", "PyPDF2>=3.0.1"])
subprocess.check_call(["pip", "install", "google-generativeai"])
subprocess.check_call(["pip", "install", "textblob>=0.17.1"])
subprocess.check_call(["pip", "install", "python-dotenv>=1.0.0"])
subprocess.check_call(["pip", "install", "genai"])
subprocess.check_call(["pip", "install", "google-cloud-aiplatform==1.34.0"])
import transformers
import torch
import os
import youtube_transcript_api
import pytube
import gradio
import PyPDF2
import pathlib
import pandas
import numpy
import textblob
import gradio as gr
from youtube_transcript_api import YouTubeTranscriptApi
import google.generativeai as genai
import requests
from textblob import TextBlob
import re
#from google.cloud import generativeai
from huggingface_hub import login
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
def install_missing_packages():
required_packages = {
"torch":">=1.11.0",
"transformers":">=4.34.0",
"youtube_transcript_api" :">=0.6.3" ,
"pytube":None,
"huggingface_hub": ">=0.19.0",
"PyPDF2": ">=3.0.1",
"textblob":">=0.17.1",
"python-dotenv":">=1.0.0",
"genai":None,
"google-generativeai": None,
"google-cloud-aiplatform":"==1.34.0"
}
for package, version in required_packages.items():
try:
__import__(package)
except ImportError:
package_name = f"{package}{version}" if version else package
subprocess.check_call(["pip", "install", package_name])
install_missing_packages()
# Configuration
hf_token = os.getenv("HF_TOKEN")
if hf_token:
login(hf_token)
else:
raise ValueError("HF_TOKEN environment variable not set.")
# GOOGLE_API_KEY = "AIzaSyAURQb9jueh3dBQ4SITgKoR0L2_33en3yU"
# YOUTUBE_API_KEY = "AIzaSyB7X-RYjZmUuDSMTQsvCfyzURw5bhqOto4"
# genai.configure(api_key=GOOGLE_API_KEY)
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
genai.configure(api_key=GOOGLE_API_KEY)
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
print("GOOGLE_API_KEY:", os.getenv("GOOGLE_API_KEY"))
print("YOUTUBE_API_KEY:", os.getenv("YOUTUBE_API_KEY"))
import streamlit as st
from youtube_transcript_api import YouTubeTranscriptApi
import google.generativeai as genai
import requests
from textblob import TextBlob
import re
# Configuration
USER_CREDENTIALS = {
"admin": "password123",
"teacher": "teach2024",
"student": "learn2024"
}
GOOGLE_API_KEY = "AIzaSyAURQb9jueh3dBQ4SITgKoR0L2_33en3yU"
YOUTUBE_API_KEY = "AIzaSyB7X-RYjZmUuDSMTQsvCfyzURw5bhqOto4"
genai.configure(api_key=GOOGLE_API_KEY)
# Database
students_data = [
(1, "Alice", "A", "Computer Science"),
(2, "Aliaa", "B", "Mathematics"),
(3, "Charlie", "A", "Machine Learning"),
(4, "Daan", "A", "Physics"),
(5, "Jhon", "C", "Math"),
(6, "Emma", "A+", "Computer Science")
]
teachers_data = [
(1, "Dr. Smith", "Math", "MS Mathematics"),
(2, "Ms. Johnson", "Science", "MSc Physics"),
(3, "Ms. Jack", "Artificial Intelligence Engineer", "MSc AI"),
(4, "Ms. Evelyn", "Computer Science", "MSc Computer Science"),
]
courses_data = [
(1, "Algebra", "Dr. Smith", "Advanced"),
(2, "Biology", "Ms. Mia", "Intermediate"),
(3, "Machine Learning", "Ms. Jack", "Intermediate"),
(4, "Computer Science", "Ms. Evelyn", "Intermediate"),
(5, "Mathematics", "Ms. Smith", "Intermediate")
]
def sanitize_text(text):
"""Remove invalid Unicode characters."""
return text.encode("utf-8", "replace").decode("utf-8")
def extract_video_id(url):
if not url:
return None
patterns = [
r'(?:v=|\/videos\/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v=|\/watch\?v=)([^#\&\?]*)'
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return match.group(1)
return None
def process_youtube_video(url="", keywords=""):
"""Process either video URL or keywords or both"""
try:
thumbnail = None
summary = ""
sentiment_label = "N/A"
recommendations = ""
if url.strip():
video_id = extract_video_id(url)
if video_id:
transcript = YouTubeTranscriptApi.get_transcript(video_id)
text = " ".join([t['text'] for t in transcript])
# Sanitize text
text = sanitize_text(text)
model = genai.GenerativeModel("gemini-pro")
summary = model.generate_content(f"Summarize this: {text}").text
sentiment = TextBlob(text).sentiment
sentiment_label = f"{'Positive' if sentiment.polarity > 0 else 'Negative' if sentiment.polarity < 0 else 'Neutral'} ({sentiment.polarity:.2f})"
thumbnail = f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg"
if keywords.strip():
recommendations = get_recommendations(keywords)
return (
thumbnail,
summary or "Enter a video URL for analysis",
sentiment_label,
recommendations or "Enter keywords for recommendations"
)
except Exception as e:
return None, f"Error: {str(e)}", "N/A", ""
def get_recommendations(keywords, max_results=5):
if not keywords:
return "Please provide search keywords"
try:
response = requests.get(
"https://www.googleapis.com/youtube/v3/search",
params={
"part": "snippet",
"q": f"educational {keywords}",
"type": "video",
"maxResults": max_results,
"relevanceLanguage": "en",
"key": YOUTUBE_API_KEY
}
).json()
results = []
for item in response.get("items", []):
title = item["snippet"]["title"]
channel = item["snippet"]["channelTitle"]
video_id = item["id"]["videoId"]
results.append(f"πΊ {title}\nπ€ {channel}\nπ https://youtube.com/watch?v={video_id}\n")
return "\n".join(results) if results else "No recommendations found"
except Exception as e:
return f"Error: {str(e)}"
# Streamlit Interface
# Streamlit Interface
st.title("π Educational Learning Management System")
# Login Page
if "logged_in" not in st.session_state:
st.session_state.logged_in = False
if not st.session_state.logged_in:
st.header("Login")
username = st.text_input("Username")
password = st.text_input("Password", type="password")
login_btn = st.button("Login")
if login_btn:
if USER_CREDENTIALS.get(username) == password:
st.session_state.logged_in = True
st.rerun() # Updated from st.experimental_rerun()
else:
st.error("Invalid credentials")
else:
st.sidebar.title("Navigation")
nav_option = st.sidebar.radio("Go to", ["Dashboard", "Students", "Teachers", "Courses", "YouTube Tool"])
logout_btn = st.sidebar.button("Logout")
if logout_btn:
st.session_state.logged_in = False
st.rerun() # Updated from st.experimental_rerun()
if nav_option == "Dashboard":
st.header("π Dashboard")
st.markdown(f"""
### System Overview
- π₯ Total Students: {len(students_data)}
- π¨βπ« Total Teachers: {len(teachers_data)}
- π Total Courses: {len(courses_data)}
### Quick Actions
- View student performance
- Access course materials
- Generate learning insights
""")
elif nav_option == "Students":
st.header("π₯ Students")
st.dataframe(
students_data,
columns=["ID", "Name", "Grade", "Program"]
)
elif nav_option == "Teachers":
st.header("π¨βπ« Teachers")
st.dataframe(
teachers_data,
columns=["ID", "Name", "Subject", "Qualification"]
)
elif nav_option == "Courses":
st.header("π Courses")
st.dataframe(
courses_data,
columns=["ID", "Name", "Instructor", "Level"]
)
elif nav_option == "YouTube Tool":
st.header("π₯ Agent for YouTube Content Exploration")
video_url = st.text_input("YouTube URL", placeholder="https://youtube.com/watch?v=...")
keywords = st.text_input("Keywords for Recommendations", placeholder="e.g., python programming, machine learning")
analyze_btn = st.button("Analyze Video")
if analyze_btn:
thumbnail, summary, sentiment, recommendations = process_youtube_video(video_url, keywords)
if thumbnail:
st.image(thumbnail, caption="Video Thumbnail")
st.subheader("π Summary")
st.text_area("Summary", summary, height=150)
st.subheader("π Content Sentiment")
st.text(sentiment)
st.subheader("π― Related Videos")
st.text_area("Recommendations", recommendations, height=150)
|