harshj0506's picture
Update app.py
d54a661 verified
import streamlit as st
import openai
import os
from fpdf import FPDF
from PIL import Image
import io
from langchain_community.document_loaders import YoutubeLoader
import pyttsx3
import requests
# Initialize OpenAI API
openai.api_key = 'sk-proj-vwPU5Rhnd9FE5KO25fNdT3BlbkFJVrEvfXZ9YxxsO5lYzLw3'
# Function to generate content using ChatGPT
def generate_content(messages):
endpoint = 'https://api.together.xyz/v1/chat/completions'
headers = {
"Authorization": "Bearer dc073523ec85f07124dd84b16504a472905c1fac5542f3bf43f9043b8162afc7",
"Content-Type": "application/json"
}
data = {
"model": "meta-llama/Llama-3-8b-chat-hf",
"max_tokens": 1024,
"temperature": 0.7,
"top_p": 0.7,
"top_k": 50,
"repetition_penalty": 1,
"stop": ["<|eot_id|>"],
"messages": messages
}
response = requests.post(endpoint, headers=headers, json=data)
if response.status_code == 200:
generated_text = response.json()['choices'][0]['message']['content']
return generated_text
else:
print(f"Error: {response.status_code} - {response.text}")
return "Error generating content"
def summarize_youtube_video(video_url, openai_api_key, max_tokens=1500):
openai.api_key = openai_api_key
# Load the transcript from the YouTube video
loader = YoutubeLoader.from_youtube_url(video_url, add_video_info=True)
transcript_documents = loader.load()
transcript_text = "\n\n".join(map(str, transcript_documents))
# Define the prompt
prompt = f"""
You are an advanced text/video summarization and explanation system. Your goal is to take input in the form of text or video and provide a concise yet comprehensive summary and explanation that captures the key content, information, and important data points.
Your summary should:
1. Be no more than 20% of the original text/video length
2. Use clear and concise language
3. Maintain an objective tone
4. Cover the main topics, key facts, and essential takeaways
5. Omit unnecessary details, filler words, and redundancies
Your explanation should:
1. Provide context and background information necessary to understand the content
2. Clarify complex concepts, technical terms, or domain-specific knowledge
3. Offer insights, analysis, and interpretation of the key points
4. Use examples, analogies, or visuals to aid comprehension where appropriate
The overall structure of your output should follow this format:
## Summary
[Concise bullet point or paragraph summary]
## Explanation
### Background/Context
[Relevant background information to set the stage]
### Key Points Explained
1. [Main point 1 with clear explanation]
2. [Main point 2 with clear explanation]
3. ...
### Analysis/Insights
[Your analysis, insights, and interpretations regarding the content]
Please maintain professionalism, accuracy, and an academic/educational tone throughout. Do not inject personal opinions or speculations unless explicitly requested.
[Transcript Text or Video Content]:
{transcript_text}
"""
# Use gpt-3.5-turbo to summarize the transcript
messages = [
{"role": "system", "content": "You are a helpful teaching assistant."},
{"role": "user", "content": prompt}
]
summary = generate_content(messages)
return summary
# Function to create a PDF
def create_pdf(content, file_path):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
for line in content.split('\n'):
pdf.multi_cell(0, 10, txt=line)
pdf_data = io.BytesIO()
pdf.output(pdf_data, dest='S')
pdf_data.seek(0)
with open(file_path, 'wb') as f:
f.write(pdf_data.getvalue())
return pdf_data
# Function to read text using text-to-speech
def read_text(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
# Function to analyze an image using OpenAI API
def analyze_image(image_file):
with open(image_file, "rb") as file:
image_data = file.read()
response = openai.Image.create(
image=image_data,
prompt="""You are an intelligent image analysis system trained to interpret and describe diagrams and graphs. Your task is to analyze the provided image and provide a detailed description of its contents, including:
1. The type of diagram or graph (e.g., bar chart, line graph, pie chart, flow diagram, etc.).
2. The title and labels of the diagram or graph, if present.
3. The variables or quantities represented on the x-axis and y-axis (for charts and graphs).
4. The overall trend or pattern depicted in the data.
5. Any specific data points, values, or components that stand out or are noteworthy.
6. The potential meaning or interpretation of the information presented in the diagram or graph.
Please provide your analysis in a clear and concise manner, ensuring that your description is easy to understand for both technical and non-technical users. If you encounter any issues or have difficulty interpreting the image, please let me know.""",
n=1,
size="1024x1024"
)
return response['data'][0]['text']
# Streamlit interface
st.title("Teaching Assistant Application")
st.sidebar.header("Options")
option = st.sidebar.selectbox(
"Choose an option",
["Generate Test Questions","Youtube Video Summeriser","Generate Project Based Learning", "Create Course Curriculum", "Create Assignments", "Create Activities"]
)
st.header(option)
if option == "Generate Test Questions":
topic = st.text_input("Enter the topic")
standard = st.text_input("Enter the standard/grade level")
if st.button("Generate"):
if topic and standard:
prompt = f"""I want you to create a worksheet for the following topic/subtopic: {topic}. The worksheet should be tailored for {standard}
The worksheet should include a mix of the following question types:
1. Multiple Choice Questions (MCQs)
- Provide 5-10 MCQs with 4 options each
- Make sure the questions cover various aspects of the topic/subtopic
- Include a mix of straightforward and challenging questions
2. Multiple Answer Questions
- Provide 3-5 questions where students need to select multiple correct answers
- These questions should test their ability to identify multiple related concepts or ideas
3. One-line Answer Questions
- Provide 3-5 questions that require a one-line answer
- These questions can test definitions, formulas, or brief explanations
4. Fill-in-the-Blanks
- Provide 3-5 statements with blank spaces for students to fill in
- These can test their understanding of key terms, concepts, or relationships
Additionally, please include the following components:
1. Worksheet Title and Instructions
- Provide a clear title for the worksheet
- Include concise instructions on how to complete the worksheet
2. Answer Key
- Provide a separate answer key at the end of the worksheet
- Include detailed explanations or workings for the answers where applicable
Please ensure that the questions are well-structured, relevant to the topic/subtopic, and
appropriate for the specified student standard. Use clear and concise language, and avoid
ambiguity or confusing phrasing.
The worksheet should be designed to assess students' understanding of the topic/subtopic
while also providing an opportunity for practice and reinforcement. Feel free to incorporate
diagrams, illustrations, or additional resources if necessary.
Please format the worksheet in a clear and organized manner, using appropriate headings,
subheadings, and spacing for better readability."""
messages = [
{"role": "system", "content": "You are a helpful teaching assistant."},
{"role": "user", "content": prompt}
]
content = generate_content(messages)
st.subheader("Generated Content")
st.write(content)
if st.button("Export to PDF"):
pdf_path = "generated_content.pdf"
pdf_data = create_pdf(content, pdf_path)
st.download_button(
label="Download PDF",
data=pdf_data.getvalue(),
file_name="generated_content.pdf",
mime="application/pdf"
)
else:
st.warning("Please enter both a topic and a standard.")
if option == "Youtube Video Summeriser" :
video_url = st.text_input("Enter the youtube video url")
if "summary" not in st.session_state:
st.session_state.summary = ""
if st.button("Summarize Video"):
if video_url:
content = summarize_youtube_video(video_url, 'sk-proj-vwPU5Rhnd9FE5KO25fNdT3BlbkFJVrEvfXZ9YxxsO5lYzLw3')
st.subheader("Generated Report")
st.session_state.summary = content
st.markdown(content)
if st.button("Export to PDF"):
pdf_path = "generated_content.pdf"
pdf_data = create_pdf(content, pdf_path)
st.download_button(
label="Download PDF",
data=pdf_data.getvalue(),
file_name="generated_content.pdf",
mime="application/pdf"
)
if option == "Generate Project Based Learning":
topic = st.text_input("Enter the topic")
standard = st.text_input("Enter the standard/grade level")
if st.button("Generate"):
if topic and standard:
prompt = f"""You are a student embarking on an exciting project-based learning experience in {topic} and standard {standard}. Your task is to design and develop a comprehensive project that demonstrates your understanding of the key concepts and skills covered in this subject area.
Your project should have the following components:
1. Project Overview:
- Provide a brief description of your project, including its purpose, goals, and the real-world problem or challenge it aims to address.
- Explain the relevance and significance of your project in relation to the subject matter.
2. Learning Objectives:
- Clearly define the specific learning objectives you aim to achieve through this project.
- Outline the key concepts, theories, principles, and skills from {topic} that you will apply and demonstrate in your project.
3. Project Plan:
- Develop a detailed plan for your project, including milestones, timelines, and specific tasks or activities you will undertake.
- Describe the research, data collection, analysis, and other methodologies you will employ.
- Identify any resources, materials, or tools you will need to complete the project successfully.
4. Expected Outcomes and Deliverables:
- Describe the tangible outcomes or deliverables you expect to produce as a result of your project (e.g., a report, presentation, prototype, model, or other artifact).
- Explain how these outcomes will demonstrate your mastery of the subject matter and achievement of the learning objectives.
5. Evaluation and Assessment:
- Propose criteria or rubrics for evaluating the quality and success of your project.
- Suggest ways in which your project can be assessed to measure your learning and understanding of {topic}.
6. Reflection and Next Steps:
- Discuss how you plan to reflect on your project experience and the lessons learned.
- Identify potential areas for further exploration or future projects related to {topic}.
Remember, project-based learning is an opportunity for you to take ownership of your learning, apply your knowledge in a practical and meaningful way, and develop valuable skills such as critical thinking, problem-solving, collaboration, and self-directed learning.
Be creative, innovative, and engage deeply with the subject matter to make the most of this learning experience."""
messages = [
{"role": "system", "content": "You are a helpful teaching assistant."},
{"role": "user", "content": prompt}
]
content = generate_content(messages)
st.subheader("Generated Content")
st.write(content)
if st.button("Export to PDF"):
pdf_path = os.path.join("generated_content.pdf")
create_pdf(content, pdf_path)
with open(pdf_path, "rb") as pdf_file:
st.download_button(
label="Download PDF",
data=pdf_file,
file_name="generated_content.pdf",
mime="application/pdf"
)
else:
st.warning("Please enter both a topic and a standard.")
elif option == "Create Course Curriculum":
subject = st.text_input("Enter the subject(s) (e.g., Biology, Physics)")
standard = st.text_input("Enter the standard/grade level")
if st.button("Generate"):
if subject:
prompt = f"""I want you to create a detailed course curriculum for the following subject(s): {subject} and following class {standard}.
The curriculum should cover all the essential topics, concepts, and subtopics within these subject areas.
The curriculum should be divided into 5 units, and each unit should have the following components:
1. Unit Overview
- A brief introduction to the unit
- Key learning objectives for the unit
2. Core Concepts and Topics
- List of core concepts and topics covered in the unit
- Detailed explanations and descriptions for each concept/topic
3. Suggested Learning Resources
- Recommended textbooks, articles, videos, or online resources for further exploration
4. Classroom Activities and Exercises
- A variety of engaging activities and exercises to reinforce the learning concepts
- These can include discussions, experiments, case studies, problem-solving exercises, etc.
5. Projects and Assessments
- Hands-on projects or assignments that allow students to apply their knowledge
- Assessments (quizzes, tests, or exams) to evaluate student understanding
6. Extension and Enrichment Opportunities
- Additional resources or activities for advanced or interested students
- Suggestions for further reading, research projects, or real-world applications
Please ensure that the curriculum is comprehensive, logically structured, and provides ample learning opportunities for students to develop a deep understanding of the subject(s).
Additionally, incorporate interdisciplinary connections where relevant, and suggest collaborative or group-based learning activities to foster teamwork and communication skills.
The curriculum should be designed for high school students.
Please provide a detailed and well-organized curriculum that follows the outlined structure.
Use appropriate headings, subheadings, and formatting to enhance readability and clarity."""
messages = [
{"role": "system", "content": "You are a helpful teaching assistant."},
{"role": "user", "content": prompt}
]
content = generate_content(messages)
st.subheader("Generated Content")
st.write(content)
if st.button("Export to PDF"):
pdf_path = os.path.join("generated_content.pdf")
create_pdf(content, pdf_path)
with open(pdf_path, "rb") as pdf_file:
st.download_button(
label="Download PDF",
data=pdf_file,
file_name="generated_content.pdf",
mime="application/pdf"
)
else:
st.warning("Please enter the subject(s).")
elif option == "Create Assignments":
topic = st.text_input("Enter the topic/keywords/goal")
standard = st.text_input("Enter the standard/grade level")
if st.button("Generate"):
if topic:
prompt = f"""Based on the provided topic/keywords/goal {topic} and standard {standard}, generate the following:
# Assignment Goal
[A clear and concise statement of the overall goal or objective of the assignment]
# Steps
1. Step 1
- Description: [Brief description of this step]
- Task/Assignment: [Specific task or assignment for students to complete in this step]
2. Step 2
- Description: [Brief description of this step]
- Task/Assignment: [Specific task or assignment for students to complete in this step]
[Add more steps as needed, with each step building upon the previous one]
# Final Deliverable
[Description of the final product, project, or outcome that students should produce by completing all the steps]
# Evaluation Criteria
[Outline the criteria or rubric that will be used to evaluate the final deliverable]
# Additional Resources
[Optional: List of any additional resources, materials, or references that students may find helpful for completing the assignment]
Human Feedback:
[Provide any feedback or additional requirements here]"""
messages = [
{"role": "system", "content": "You are a helpful teaching assistant."},
{"role": "user", "content": prompt}
]
content = generate_content(messages)
st.subheader("Generated Content")
st.write(content)
if st.button("Export to PDF"):
pdf_path = os.path.join("generated_content.pdf")
create_pdf(content, pdf_path)
with open(pdf_path, "rb") as pdf_file:
st.download_button(
label="Download PDF",
data=pdf_file,
file_name="generated_content.pdf",
mime="application/pdf"
)
else:
st.warning("Please enter the topic/keywords/goal.")
elif option == "Create Activities":
topic = st.text_input("Enter the topic/keywords (e.g., Water cycle)")
standard = st.text_input("Enter the standard/grade level")
if st.button("Generate"):
if topic:
prompt = f"""Based on the provided topic/keywords: {topic} and standard: {standard}, generate the following:
# Topic Name / Keywords
# Activities
1. [Activity 1 Name]
[Detailed explanation of the activity]
Things needed:
- [List of materials or resources required]
2. [Activity 2 Name]
[Detailed explanation of the activity]
Things needed:
- [List of materials or resources required]
[Add more activities as needed]
# Remarks for Teachers
- [Important considerations, grouping strategies, or additional instructions for teachers]
# Learning Experience
[Description of the overall learning experience, including the sequence of activities and estimated time required]
# Homework/Assignment
[Description of any homework, assignments, or additional work for students to complete outside the classroom]
Human Feedback:
[Provide any feedback or additional requirements here]"""
messages = [
{"role": "system", "content": "You are a helpful teaching assistant."},
{"role": "user", "content": prompt}
]
content = generate_content(messages)
st.subheader("Generated Content")
st.write(content)
if st.button("Export to PDF"):
pdf_path = os.path.join("generated_content.pdf")
create_pdf(content, pdf_path)
with open(pdf_path, "rb") as pdf_file:
st.download_button(
label="Download PDF",
data=pdf_file,
file_name="generated_content.pdf",
mime="application/pdf"
)
else:
st.warning("Please enter the topic/keywords.")
# Streamlit app code
elif option == "Describe and Discuss Image":
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image', use_column_width=True)
if st.button("Describe and Discuss"):
# Convert image to byte array for embedding in the prompt
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
# Prompt for describing and discussing the image
prompt = f"""Analyze the following image and provide a detailed description and discussion:
{img_byte_arr}
Please describe the key elements in the image, discuss its possible context or background, and suggest how it could be used in an educational setting."""
messages = [
{"role": "system", "content": "You are a helpful teaching assistant skilled in image analysis."},
{"role": "user", "content": prompt}
]
content = generate_content(messages)
st.subheader("Generated Content")
st.write(content)
if st.button("Export to PDF"):
pdf_path = os.path.join("generated_content.pdf")
create_pdf(content, pdf_path)
with open(pdf_path, "rb") as pdf_file:
st.download_button(
label="Download PDF",
data=pdf_file,
file_name="generated_content.pdf",
mime="application/pdf"
)