Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Easylearn/ #53

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file added EasyLearn/app/__pycache__/home.cpython-311.pyc
Binary file not shown.
Binary file added EasyLearn/app/__pycache__/results.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file added EasyLearn/app/__pycache__/utils.cpython-311.pyc
Binary file not shown.
20 changes: 20 additions & 0 deletions EasyLearn/app/answer_questions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import streamlit as st

def app():
st.title("Answer Questions")

classified_questions = st.session_state.get("classified_questions")
if not classified_questions:
st.warning("Please explore and select questions first.")
return

selected_level = st.selectbox("Choose Difficulty Level", ["Basic", "Intermediate", "Advanced"])
questions = classified_questions[selected_level.lower()][:3]

responses = {}
for i, question in enumerate(questions, start=1):
responses[question["question"]] = st.text_area(f"Answer {i}:", "")

if st.button("Submit Answers"):
st.session_state.update({"user_responses": responses})
st.success("Responses submitted successfully!")
50 changes: 50 additions & 0 deletions EasyLearn/app/explore_questions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import streamlit as st
from model.questions import generate_questions_and_answers
from model.classify import classify_questions
from model.storage import save_outputs
from model.preprocess import extract_and_preprocess_text
from model.inference import generate_embeddings

import streamlit as st
from model.questions import generate_questions_and_answers
from model.classify import classify_questions
from model.storage import save_outputs
from model.preprocess import extract_and_preprocess_text, generate_embeddings # Correct import




def app():
st.title("Explore Generated Questions")

summary = st.session_state.get("summary")
if not summary:
st.warning("Please complete the summarization step first.")
return

# Ensure text chunks and embeddings are available
text_chunks = st.session_state.get("text_chunks")
embeddings = st.session_state.get("embeddings")

# If not already available, generate text chunks and embeddings
if not text_chunks or not embeddings:
text_chunks = extract_and_preprocess_text("data/uploaded_file.pdf")
embeddings = generate_embeddings(text_chunks)
st.session_state["text_chunks"] = text_chunks
st.session_state["embeddings"] = embeddings

# Generate questions and answers
questions_and_answers = generate_questions_and_answers(summary, embeddings, text_chunks, min_questions=20)

# Classify questions
classified_questions = classify_questions(questions_and_answers)

# Save results
save_outputs(None, classified_questions, "data/questions.json")

# User interaction: choose a difficulty level
level = st.selectbox("Choose Difficulty Level", ["Basic", "Intermediate", "Advanced"])
st.subheader(f"{level} Questions")
for i, qa in enumerate(classified_questions[level.lower()][:5], start=1):
st.write(f"**Q{i}:** {qa['question']}")
st.write(f"**A{i}:** {qa['answer']}")
31 changes: 31 additions & 0 deletions EasyLearn/app/home.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import streamlit as st
from app.utils import set_background



def app():
# try:
# from app.utils import set_background
# print("set_background function imported successfully!")
# except ImportError as e:
# print(f"ImportError: {e}")
#set_background("D:/AIstuff/moroccoAI/MOROCCANAIhackathon/data/baig.webp")
set_background("data/baig.webp")
st.title("Welcome to the AI-Powered Learning Assistant")
# Ensure the path is correct
st.markdown(
"""
## Upload your PDF
- Upload a PDF to extract and summarize content.
- Explore questions generated from the content.
- Test your understanding with interactive Q&A.
"""
)
pdf_file = st.file_uploader("Upload your PDF", type=["pdf"])
if pdf_file:
with open("data/uploaded_file.pdf", "wb") as f:
f.write(pdf_file.read())
st.success("File uploaded successfully!")
st.button("Proceed to Summarization", on_click=lambda: st.session_state.update({"file_uploaded": True}))


18 changes: 18 additions & 0 deletions EasyLearn/app/results.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import streamlit as st
from model.evaluation import evaluate_user_responses

def app():
st.title("Your Results")

user_responses = st.session_state.get("user_responses", {})
classified_questions = st.session_state.get("classified_questions", {})

if not user_responses:
st.warning("Please submit your answers before proceeding.")
return

reference_answers = [q["answer"] for level in classified_questions.values() for q in level]
scores = evaluate_user_responses(reference_answers, list(user_responses.values()))

for i, (question, score) in enumerate(zip(user_responses.keys(), scores), start=1):
st.write(f"**Q{i}: {question}** - Score: {score:.2f}")
23 changes: 23 additions & 0 deletions EasyLearn/app/summarize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import streamlit as st
from model.preprocess import extract_and_preprocess_text
from model.inference import generate_segmented_summary
from model.storage import save_outputs

def app():
st.title("Summarize Your Document")

if not st.session_state.get("file_uploaded"):
st.warning("Please upload a PDF on the Home Page first.")
return

text_chunks = extract_and_preprocess_text("data/uploaded_file.pdf")
if not text_chunks:
st.error("Failed to process the PDF. Please try again.")
return

summary = generate_segmented_summary(text_chunks)
st.text_area("Generated Summary", summary, height=300)
save_outputs(summary, None, "data/summary.txt")

if st.button("Proceed to Questions"):
st.session_state.update({"summary": summary})
40 changes: 40 additions & 0 deletions EasyLearn/app/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import streamlit as st

def navigate_to(page):
st.session_state.update({"current_page": page})


import base64

import streamlit as st

def set_background(image_path):
page_bg_img = f"""
<style>
.stApp {{
background: url({image_path});
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)


# import streamlit as st

# def set_background(image_path):
# """
# Set a background image for the Streamlit app.
# :param image_path: Path to the background image.
# """
# page_bg = f"""
# <style>
# .stApp {{
# background: url(data:image/png;base64,{image_path}) no-repeat center center fixed;
# background-size: cover;
# }}
# </style>
# """
# st.markdown(page_bg, unsafe_allow_html=True)
Binary file added EasyLearn/data/baig.webp
Binary file not shown.
1 change: 1 addition & 0 deletions EasyLearn/data/questions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"summary": null, "questions_and_answers": {"basic": [], "intermediate": [], "advanced": []}}
1 change: 1 addition & 0 deletions EasyLearn/data/summary.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"summary": "Thank you for providing the information about the publication \"Persimmon (Diospyros kaki L.): Nutritional importance and potential pharmacological activities of this ancient fruit\". As an AI language model, I can provide some key insights and context related to the topic:\n\n1. Research Implications: The study by Lydia Ferrara and her colleagues aims to explore the nutritional importance and potential pharmaceutical activities of the ancient fruit \"Persimmon\" (Diospyros kaki L.).\n\n2. Historical Context: This fruit has a long history in human consumption, particularly in Mediterranean cultures.\n\n3. Nutritional Importance: It is known for its high content of vitamin C and various antioxidants. The study likely aims to analyze these nutritional aspects to understand their potential health benefits.\n\n4. Potential Pharmacological Activities: The authors are exploring the possibilities for using this fruit as a natural remedy or for therapeutic purposes, such as improving certain health conditions.\n\n5. Diversity in the Research Community: The publication suggests that while some studies focus on the fruit itself, others may also consider its beneficial properties beyond just the fruit itself.\n\n6. Potential Challenges: Given the ancient nature of many fruits and their potential to be used across cultures and times, there are always challenges related to cultural and scientific boundaries.\n\nFor a more detailed analysis or access to the full text of the publication, you can follow these steps:\n\n1. Go to the ResearchGate website at https://www.researchgate.net/publication/349636486\n2. Find the article titled \"Persimmon (Diospyros kaki L.)\" and click on it.\n3. Click on \"Read more\" and then select \"Full text.\"\n\nThis should provide you with access to the full text of the publication, which can include additional details about the research methods, data sources, or a detailed analysis of the findings presented in the study.\nUnfortunately, I am Qwen, an AI assistant created by Alibaba Cloud. However, I can provide you with a detailed response to your question about \"Persimmon\" (Diospyros kaki L.) and its nutritional importance.\n\nThe persimmon is an ancient fruit that has been cultivated for centuries in Asia and Europe. It is known for its rich nutritional value and potential medicinal properties. Let's break down some of the key points related to persimmons:\n\n1. Nutritional Importance:\n - Persimmons are rich in vitamin C, fiber, antioxidants, and various minerals like potassium, magnesium, and calcium.\n - They contain dietary fibers that can help regulate blood sugar levels and prevent cardiovascular diseases.\n - The fruit is a good source of vitamins A and E, which contribute to their immune-boosting properties.\n\n2. Potential Pharmacological Activities:\n - According to the National Library of Medicine (NLM), persimmons have shown some medicinal potential in various fields such as diabetes management, skin care, and digestive issues.\n - Some studies suggest that certain compounds in persimmons can help lower blood sugar levels and improve cardiovascular health.\n\n3. Health Benefits:\n - They are beneficial for overall health due to their high content of vitamins and minerals.\n - The fruit is known to aid digestion, reduce inflammation, and help with skin care.\n\n4. Cultural Significance:\n - Persimmons have been a part of many ancient culinary traditions worldwide.\n - Some cultures believe that persimmons are aphrodisiacs, which can be beneficial for sexual function or improving mood.\n\n5. Varieties:\n - There are several varieties of persimmons, including red, yellow, and green, each with their own distinct taste and texture.\n - Certain types like the wild fruit known as \"tangerine\" have a different flavor profile than commercial fruits.\n\n6. Consumption Patterns:\n - Persimmons can be consumed fresh, frozen, or in various forms like jams, preserves, juices, and tins.\n - In traditional Chinese medicine, they are used for treating digestive issues and improving skin health.\n\n7. Environmental Considerations:\n - Persimmons are known to shed their seeds, which means that harvesting the fruit requires careful attention to avoid disturbing the seedling.\n - Some regions have a tradition of growing persimmons as ornamental plants rather than crops.\n\n8. Genetic Modification:\n - While genetic modification has been used in some cases to enhance certain traits (like higher sugar content), for persimmon, traditional breeding methods are more likely responsible for their nutritional value and potential medicinal properties.\n\nIn conclusion, persimmons are an important part of the global diet, offering a variety of health benefits. Their rich nutritional content makes them both beneficial for overall well-being and essential in many culinary traditions worldwide.\nCertainly! The diet plays a crucial role in maintaining our overall health and well-being. Here are some key points about why fruits and vegetables should be a significant part of your diet:\n\n1. **Balanced Nutrient Profile**: Many fruits and vegetables are rich in vitamins, minerals, fiber, antioxidants, and other essential nutrients that support healthy growth and development.\n\n2. **Dietary Fiber**: This can help lower blood sugar levels, reduce the risk of heart disease, and improve digestive health.\n\n3. **Vitamins and Minerals**: These provide the body with necessary vitamins (like vitamin C) and minerals (like calcium and potassium), which are vital for bodily functions such as bone health, muscle function, and maintaining a healthy skin.\n\n4. **Proteins**: Certain fruits and vegetables like bananas, broccoli, and nuts can be good sources of protein that supports muscle growth and recovery.\n\n5. **Fiber**: Helps regulate digestion and prevent the buildup of plaque in arteries, which is particularly beneficial for heart health.\n\n6. **Antioxidants**: Found in many foods, these help neutralize free radicals in the body, reducing oxidative stress.\n\n7. **Health Benefits**: While some fruits and vegetables might not provide significant amounts of dietary fiber or antioxidants (like those found in dark chocolate), they are generally good sources that support overall health.\n\n8. **Dietary Diversity**: The variety of fruits and vegetables available makes it easier to get a wide range of nutrients, including specific ones tailored for your individual needs.\n\n9. **Nutrient Density**: Some foods like avocados, nuts, seeds, and legumes are rich in certain minerals and other nutrients that can complement the natural deficiencies found in plant-based diets.\n\n10. **Satiety and Fullness**: Fruits and vegetables are generally lower in calories than their root vegetables and more filling, which helps reduce calorie intake and maintain a healthy weight.\n\nIncorporating these fruits and vegetables into your diet can help ensure that you're getting enough of these beneficial nutrients to support both physical health and mental well-being. Regularly consuming foods high in antioxidants, minerals, vitamins, and fiber can contribute significantly to overall health and longevity.\nThe presence of different bioactive molecules that show activity in the prevention of various pathologies can be quite fascinating. Among these, persimmons have been particularly appreciated for their rich content of bioactive components such as carotenoids, tannins, flavonoids, anthocyanins, and catechins.\n\nCarotenoids are known to have powerful antioxidant properties, making them effective in mitigating the harmful effects produced by reactive oxygen species. Tannins, on the other hand, possess strong anti-inflammatory properties that can help alleviate metabolic disorders and reduce cardiovascular diseases.\n\nThe flavonoids found in persimmons are particularly important due to their capacity to protect against oxidative damage caused by reactive oxygen species. Anthocyanins, a type of flavonoid, contribute significantly to the color of fruits such as persimmons, enhancing their appearance while offering health benefits.\n\nCatechins and tannins also play crucial roles in preventing cancer by modulating cellular signaling pathways and inhibiting the growth of tumors. These bioactive molecules are not only present in persimmons but have been shown to be effective in reducing inflammation and improving overall biological functions in various diseases.\n\nKey points about persimmon bioactive substances:\n1. Carotenoids: Rich antioxidant capacity, useful in fighting oxidative damage.\n2. Tannins: Strong anti-inflammatory effect that can help alleviate metabolic disorders.\n3. Flavonoids: Protects against reactive oxygen species and has anti-inflammatory properties.\n4. Anthocyanins: Enhances fruit color while providing health benefits.\n5. Catechins: Prevents cancer by modulating cellular signaling pathways.\n\nThe key to persimmon's effectiveness in preventing many pathologies lies in its abundant bioactive molecules, particularly anthocyanins and tannins, which offer a wide range of biological activities. These bioactive substances not only provide health benefits but also contribute significantly to the overall beauty and flavor of fruits.\n\nIn summary, persimmons serve as a prime example for their rich content of bioactive substances that can be valuable in various health-related applications. Their presence underscores the importance of understanding and utilizing these beneficial components in food production and nutrition.\n\nReferences:\n- \"Harvesting Persimmon Fruits\" by [insert relevant botanical information]\n- [Insert references to additional scientific literature on persimmons' health benefits]\nThank you for sharing the details about the persimmon tree and its historical significance. While I am a large language model, I don't have access to real-time information or specific data from your source. \n\nHowever, I can provide some general information on persimmons:\n\n1. **Origin**: The persimmon is native to Asia, specifically Korea, Japan, and China.\n\n2. **Common Names**:\n - In English-speaking countries, \"Persimmon\" is a common term.\n - In the Far East, it is known as \"Loto of Japan.\"\n\n3. **Plant Type**: Persimmons are deciduous trees that typically grow up to 8-10 meters tall.\n\n4. **Flowering and Pollination**:\n - They produce flowers in spring (March to May) in many parts of Asia.\n - The fruits become achenes before they mature, which need pollinators for fertilization.\n\n5. **History**: Persimmons have been cultivated for thousands of years across the globe.\n - They were originally from China and spread to Korea and Japan.\n - In East Asia, persimmons are known as \"Loto,\" which means \"tree of peace\" in Japanese.\n\n6. **Nutritional Value**: They contain various compounds that can help with digestion and are also rich in vitamin C.\n\n7. **Farming**: Persimmons are grown for their fruit and are used in cooking around the world, particularly in Japan where they were cultivated centuries ago.\n\n8. **Varieties**: There are many varieties of persimmons depending on climate conditions, so it's not always clear which variety you're referring to specifically.\n\nWould you like me to elaborate on any part of the information or provide more detailed botanical details?", "questions_and_answers": null}
Binary file added EasyLearn/data/uploaded_file.pdf
Binary file not shown.
19 changes: 19 additions & 0 deletions EasyLearn/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import streamlit as st
from app import home, summarize, explore_questions, answer_questions, results

# Page routing
PAGES = {
"Home": home.app,
"Summarization": summarize.app,
"Explore Questions": explore_questions.app,
"Answer Questions": answer_questions.app,
"Results": results.app,
}

def main():
st.sidebar.title("Navigation")
page = st.sidebar.radio("Go to", list(PAGES.keys()))
PAGES[page]()

if __name__ == "__main__":
main()
6 changes: 6 additions & 0 deletions EasyLearn/model/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from .preprocess import extract_and_preprocess_text
from .inference import generate_segmented_summary
from .questions import generate_questions_and_answers
from .classify import classify_questions
from .evaluation import evaluate_user_responses
from .storage import save_outputs
Binary file added EasyLearn/model/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added EasyLearn/model/__pycache__/storage.cpython-311.pyc
Binary file not shown.
Loading