File size: 5,918 Bytes
87982ed
 
 
 
bc5e078
 
 
 
 
 
 
 
 
 
 
 
87982ed
 
 
 
 
 
 
 
bc5e078
 
 
 
87982ed
 
 
 
 
 
 
 
 
bc5e078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87982ed
bc5e078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87982ed
 
bc5e078
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
import gradio as gr
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import openai
import matplotlib.pyplot as plt
from io import BytesIO
import base64
import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Access the API key from Hugging Face Secrets
openai.api_key = os.environ.get("OPENAI_API_KEY")

# Sample dataset of resources
resources = pd.DataFrame({
    "Resource": ["Python Tutorial", "Math Basics", "Data Structures", "Machine Learning Intro"],
    "Type": ["Video", "Article", "Video", "Video"],
    "Learning Style": ["Visual", "Reading", "Visual", "Visual"]
})

# Global variables
tasks = []
points = 0

# Function to recommend resources
def recommend_resources(learning_style):
    vectorizer = TfidfVectorizer()
    tfidf_matrix = vectorizer.fit_transform(resources["Learning Style"])
    user_vector = vectorizer.transform([learning_style])
    similarities = cosine_similarity(user_vector, tfidf_matrix)
    recommended_index = similarities.argmax()
    return resources.iloc[recommended_index]

# Function to add a task
def add_task(task, deadline, priority):
    global tasks
    tasks.append({"Task": task, "Deadline": deadline, "Priority": priority, "Completed": False})
    return "Task added successfully!"

# Function to mark a task as completed
def mark_completed(task_index):
    global tasks, points
    if 0 <= task_index < len(tasks):
        tasks[task_index]["Completed"] = True
        points += 10  # Award 10 points for completing a task
        return f"Task marked as completed! You earned 10 points. Total points: {points}"
    return "Invalid task index."

# Function to visualize progress
def show_progress():
    completed = sum(1 for task in tasks if task["Completed"])
    remaining = len(tasks) - completed
    
    # Create a progress chart
    plt.bar(["Completed", "Remaining"], [completed, remaining], color=["green", "red"])
    plt.title("Study Progress")
    buffer = BytesIO()
    plt.savefig(buffer, format="png")
    buffer.seek(0)
    image_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
    plt.close()
    return f"data:image/png;base64,{image_base64}"

# Function to interact with the chatbot
def chatbot(user_input):
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=user_input,
        max_tokens=50
    )
    return response.choices[0].text.strip()

# Function to sync tasks with Google Calendar
def sync_with_calendar():
    creds = None
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", ["https://www.googleapis.com/auth/calendar"])
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", ["https://www.googleapis.com/auth/calendar"])
            creds = flow.run_local_server(port=0)
        with open("token.json", "w") as token:
            token.write(creds.to_json())
    
    service = build("calendar", "v3", credentials=creds)
    for task in tasks:
        event = {
            "summary": task["Task"],
            "start": {"dateTime": task["Deadline"] + "T09:00:00", "timeZone": "UTC"},
            "end": {"dateTime": task["Deadline"] + "T10:00:00", "timeZone": "UTC"},
        }
        event = service.events().insert(calendarId="primary", body=event).execute()
    return "Tasks synced with Google Calendar!"

# Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# AI-Powered Study Assistant")
    
    with gr.Tab("Task Management"):
        with gr.Row():
            task_input = gr.Textbox(label="Task")
            deadline_input = gr.Textbox(label="Deadline (YYYY-MM-DD)")
            priority_input = gr.Textbox(label="Priority (High/Medium/Low)")
        add_task_button = gr.Button("Add Task")
        task_output = gr.Textbox(label="Output")
        add_task_button.click(add_task, inputs=[task_input, deadline_input, priority_input], outputs=task_output)
        
        with gr.Row():
            task_index_input = gr.Number(label="Task Index to Mark as Completed")
            mark_completed_button = gr.Button("Mark Completed")
        mark_completed_output = gr.Textbox(label="Output")
        mark_completed_button.click(mark_completed, inputs=task_index_input, outputs=mark_completed_output)
        
        gr.Markdown("### Tasks")
        task_list = gr.Dataframe(headers=["Task", "Deadline", "Priority", "Completed"], value=tasks)
    
    with gr.Tab("Progress Tracking"):
        progress_button = gr.Button("Show Progress")
        progress_image = gr.Image(label="Progress Chart")
        progress_button.click(show_progress, outputs=progress_image)
    
    with gr.Tab("Chatbot"):
        chatbot_input = gr.Textbox(label="Ask a question:")
        chatbot_output = gr.Textbox(label="Chatbot Response")
        chatbot_button = gr.Button("Ask")
        chatbot_button.click(chatbot, inputs=chatbot_input, outputs=chatbot_output)
    
    with gr.Tab("Recommendations"):
        learning_style_input = gr.Textbox(label="Enter your preferred learning style (Visual/Reading):")
        recommendation_output = gr.Textbox(label="Recommended Resource")
        recommend_button = gr.Button("Get Recommendation")
        recommend_button.click(recommend_resources, inputs=learning_style_input, outputs=recommendation_output)
    
    with gr.Tab("Google Calendar Sync"):
        sync_button = gr.Button("Sync with Google Calendar")
        sync_output = gr.Textbox(label="Output")
        sync_button.click(sync_with_calendar, outputs=sync_output)

# Launch the app
demo.launch()