File size: 7,476 Bytes
96ab4ac
3ff70e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96ab4ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff70e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96ab4ac
3ff70e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96ab4ac
3ff70e7
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
import gradio as gr
import wikipedia
from langchain_tavily import TavilySearch
from transformers import pipeline
from llama_index.llms.nebius import NebiusLLM
from PyPDF2 import PdfReader
from textblob import TextBlob

import os
from dotenv import load_dotenv

load_dotenv() 

os.environ["TAVILY_API_KEY"] = os.getenv("TAVILY_API_KEY")
NEBIUS_API_KEY = os.getenv("NEBIUS_API_KEY")
llm = NebiusLLM(
    api_key=NEBIUS_API_KEY, model="meta-llama/Meta-Llama-3.1-70B-Instruct-fast"
)

summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

def letter_counter(word, letter):
    """
    Count the number of occurrences of a letter in a word or text.

    Args:
        word (str): The input text to search through
        letter (str): The letter to search for

    Returns:
        str: A message indicating how many times the letter appears
    """
    word = word.lower()
    letter = letter.lower()
    count = word.count(letter)
    return count

def web_search(query):
    """
    Web search using TavilySearch, formatted output.
    """
    tool = TavilySearch(max_results=5, topic="general")
    response = tool.invoke(query)
    return f"Results for '{query}': '{response}'"

def wikipedia_search(query):
    try:
        summary = wikipedia.summary(query, sentences=2)
        return summary
    except Exception as e:
        return f"Error: {e}"

def text_summarizer(text):
    """
    Summarizes the input text using a pre-trained model.
    """
    try:
        summary = summarizer(text, max_length=100, min_length=25, do_sample=False)
        return summary[0]['summary_text']
    except Exception as e:
        return f"Error: {e}"
    
def generate_quiz_with_difficulty(file, difficulty):
    """
    Generates quiz questions and answers from the uploaded file with a specified difficulty level.
    """
    try:
        text = extract_text_from_file(file)
        prompt = f"""
        You are a quiz generator. Based on the following text, create 3 quiz questions and answers.
        The difficulty level should be '{difficulty}'. 
        Text: {text}
        Format the output as:
        Q1: <question>
        A1: <answer>
        Q2: <question>
        A2: <answer>
        Q3: <question>
        A3: <answer>
        """
        response = llm.complete(prompt)
        return response.choices[0].text.strip()
    except Exception as e:
        return f"Error: {e}"
    
    from PyPDF2 import PdfReader

def extract_text_from_file(file):
    """
    Extracts text from a PDF or text file.

    Args:
        file: The uploaded file object.

    Returns:
        str: Extracted text from the file.
    """
    try:
        # Check if the file is a PDF
        if file.name.endswith(".pdf"):
            reader = PdfReader(file)
            text = ""
            for page in reader.pages:
                text += page.extract_text()
            return text
        # Check if the file is a text file
        elif file.name.endswith(".txt"):
            return file.read().decode("utf-8")
        else:
            return "Unsupported file format. Please upload a PDF or text file."
    except Exception as e:
        return f"Error extracting text: {e}"

def essay_validator(essay):
    """
    Validates an essay based on grammar, spelling, and word count.
    """
    try:
        # Check word count
        word_count = len(essay.split())
        if word_count < 100:
            return "Essay is too short. Minimum word count is 100."
        elif word_count > 1000:
            return "Essay is too long. Maximum word count is 1000."

        # Check grammar and spelling using TextBlob
        blob = TextBlob(essay)
        corrected_essay = blob.correct()
        grammar_errors = len(blob.sentences) - len(corrected_essay.sentences)

        # Return validation results
        return f"Word Count: {word_count}\nGrammar Errors: {grammar_errors}\nCorrected Essay:\n{corrected_essay}"
    except Exception as e:
        return f"Error validating essay: {e}"
    
custom_css = """
/* Color for active tab */
.gr-tabitem.selected {
    background: #1976d2 !important;
    color: #fff !important;
}
/* Color for inactive tabs */
.gr-tabitem {
    background: #f0f0f0 !important;
    color: #222 !important;
}
"""

with gr.Blocks(title="MCP server", css=custom_css) as demo:
    gr.Markdown(
        """
        # Educational MCP Server

        Welcome to the Educational MCP Server!  
        This platform provides a suite of AI-powered tools to support your learning and research:

        - **Web Search**: Search the web for up-to-date information using TavilySearch.
        - **Wikipedia Search**: Quickly retrieve concise summaries from Wikipedia.
        - **Text Summarizer**: Summarize long texts into shorter, easy-to-read versions.
        - **Quiz Generator**: Upload a PDF or text file and generate quiz questions at your chosen difficulty.
        - **Essay Validator**: Check your essay for grammar, spelling, and word count.

        Select a tab below to get started!
        """
    )
    gr.Markdown("# MCP server")
    with gr.Tabs():
        with gr.TabItem("Web Search"):
            gr.Markdown("### Web Search")
            search_input = gr.Textbox(label="Search Query")
            search_output = gr.Textbox(label="Results")
            search_btn = gr.Button("Search")
            search_btn.click(
                web_search,
                inputs=search_input,
                outputs=search_output
            )
        with gr.TabItem("Wikipedia Search"):
            gr.Markdown("### Wikipedia Search")
            wiki_input = gr.Textbox(label="Search Wikipedia")
            wiki_output = gr.Textbox(label="Result")
            wiki_btn = gr.Button("Search")
            wiki_btn.click(
                wikipedia_search,
                inputs=wiki_input,
                outputs=wiki_output
            )
        with gr.TabItem("Text Summarizer"):
            gr.Markdown("### Text Summarizer")
            sum_input = gr.Textbox(label="Enter text to summarize")
            sum_output = gr.Textbox(label="Summary")
            sum_btn = gr.Button("Summarize")
            sum_btn.click(
                text_summarizer,
                inputs=sum_input,
                outputs=sum_output
            )
        with gr.TabItem("Quiz Generator"):
            gr.Markdown("### Quiz Generator")
            file_input = gr.File(label="Upload a PDF or Text File")
            difficulty_input = gr.Dropdown(
            label="Select Difficulty Level",
            choices=["Easy", "Medium", "Hard"],
            value="Easy"
            )
            quiz_output = gr.Textbox(label="Quiz Questions and Answers", lines=10)
            quiz_btn = gr.Button("Generate Quiz")
            quiz_btn.click(
               generate_quiz_with_difficulty,
               inputs=[file_input, difficulty_input],
               outputs=quiz_output
            )  
        with gr.TabItem("Essay Validator"):
            gr.Markdown("### Essay Validator")
            essay_input = gr.Textbox(label="Enter your essay", lines=10, placeholder="Paste your essay here...")
            essay_output = gr.Textbox(label="Validation Results", lines=10)
            essay_btn = gr.Button("Validate Essay")
            essay_btn.click(
                essay_validator,
                inputs=essay_input,
                outputs=essay_output
            )    
if __name__ == "__main__":
    demo.launch(mcp_server=True)