Spaces:
Running
Running
File size: 33,851 Bytes
0536cec fadbeb2 d0a1189 16d62e2 24d01e0 69d2db7 fadbeb2 69d2db7 516038a 69d2db7 516038a 69d2db7 7b6b0f6 69d2db7 0536cec e8893c1 69d2db7 16d62e2 4224594 fadbeb2 0536cec fadbeb2 7b6b0f6 69d2db7 7b6b0f6 69d2db7 516038a 69d2db7 0536cec 69d2db7 0536cec 16d62e2 69d2db7 16d62e2 69d2db7 16d62e2 69d2db7 0536cec 69d2db7 0536cec 516038a 16d62e2 516038a 0536cec 516038a 24d01e0 69d2db7 bf91d2a 69d2db7 bf91d2a 69d2db7 0536cec 69d2db7 0536cec 69d2db7 24d01e0 e8893c1 24d01e0 e8893c1 24d01e0 e8893c1 89fbf1a 0536cec d0a1189 82e6d45 d0a1189 82e6d45 d0a1189 82e6d45 d0a1189 82e6d45 d0a1189 82e6d45 d0a1189 82e6d45 d0a1189 0536cec 69d2db7 7b6b0f6 16d62e2 516038a 7b6b0f6 516038a 16d62e2 7b6b0f6 516038a 7b6b0f6 516038a 16d62e2 516038a 7b6b0f6 69d2db7 4224594 16d62e2 69d2db7 fadbeb2 69d2db7 4224594 69d2db7 fadbeb2 69d2db7 4224594 69d2db7 4224594 69d2db7 4224594 16d62e2 69d2db7 fadbeb2 4224594 fadbeb2 4224594 fadbeb2 4224594 fadbeb2 69d2db7 4224594 69d2db7 4224594 16d62e2 69d2db7 fadbeb2 4224594 fadbeb2 4224594 fadbeb2 4224594 69d2db7 4224594 69d2db7 4224594 16d62e2 fadbeb2 4224594 fadbeb2 516038a 4224594 fadbeb2 4224594 fadbeb2 4224594 fadbeb2 69d2db7 16d62e2 69d2db7 0536cec 16d62e2 0536cec 16d62e2 0536cec 16d62e2 0536cec 16d62e2 0536cec 24d01e0 0536cec 24d01e0 16d62e2 bf91d2a 16d62e2 bf91d2a 16d62e2 e8893c1 24d01e0 e8893c1 24d01e0 0536cec d0a1189 0536cec e8893c1 16d62e2 fadbeb2 69d2db7 |
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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 |
from itertools import permutations
from pymongo import MongoClient
from collections import Counter
from dotenv import load_dotenv
from Purify import PurifyHtml
from typing import Literal
from bson import ObjectId
from io import StringIO
import statistics
import datetime
import requests
import hashlib
import random
import base64
import gradio
import string
import json
import sys
import os
load_dotenv()
MemoryPassword = os.getenv('MEMORY_PASSWORD')
MongoURI = os.getenv('MONGO_URI')
DatabaseName = 'MCP-Utilities'
CollectionName = 'Memories'
Headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
Categories = {
'Any Category': 'any',
'General Knowledge': '9',
'Entertainment: Books': '10',
'Entertainment: Film': '11',
'Entertainment: Music': '12',
'Entertainment: Musicals & Theatres': '13',
'Entertainment: Television': '14',
'Entertainment: Video Games': '15',
'Entertainment: Board Games': '16',
'Science & Nature': '17',
'Science: Computers': '18',
'Science: Mathematics': '19',
'Mythology': '20',
'Sports': '21',
'Geography': '22',
'History': '23',
'Politics': '24',
'Art': '25',
'Celebrities': '26',
'Animals': '27',
'Vehicles': '28',
'Entertainment: Comics': '29',
'Science: Gadgets': '30',
'Entertainment: Japanese Anime & Manga': '31',
'Entertainment: Cartoon & Animations': '32'
}
Difficulties = {
'Any Difficulty': 'any',
'Easy': 'easy',
'Medium': 'medium',
'Hard': 'hard'
}
EightBallResponses = {
'Affirmative': [
'It is certain.',
'It is decidedly so.',
'Without a doubt.',
'Yes - definitely.',
'You may rely on it.',
'As I see it, yes.',
'Most likely.',
'Outlook good.',
'Yes.',
'Signs point to yes.'
],
'Non-committal': [
'Reply hazy, try again.',
'Ask again later.',
'Better not tell you now.',
'Cannot predict now.',
'Concentrate and ask again.'
],
'Negative': [
'Don\'t count on it.',
'My sources say no.',
'Very doubtful.',
'Outlook not so good.',
'My reply is no.'
]
}
try:
Client = MongoClient(MongoURI)
Database = Client[DatabaseName]
Collection = Database[CollectionName]
Client.server_info()
print('Connected to MongoDB successfully.')
except Exception as e:
print(f'Error connecting to MongoDB: {str(e)}')
Collection = None
Theme = gradio.themes.Citrus( # type: ignore
primary_hue='blue',
secondary_hue='blue',
radius_size=gradio.themes.sizes.radius_xxl, # type: ignore
font=[gradio.themes.GoogleFont('Nunito'), 'Arial', 'sans-serif'] # type: ignore
).set(
link_text_color='blue'
)
# โญโโโโโโโโโโโโโโโโโโโโโโฎ
# โ General Tools โ
# โฐโโโโโโโโโโโโโโโโโโโโโโฏ
def Weather(Location: str) -> str:
'''
Get the current weather for a specified location.
Args:
Location (str): The location for which to get the weather. E.g., "London", "France", "50.85045,4.34878" "~NASA"
Returns:
str: The current weather.".
'''
return requests.get(f'https://wttr.in/{Location}?A&format=4', headers=Headers).text
def Date() -> str:
'''Get the current date and time.
Returns:
str: The current date and time in the format "YYYY-MM-DD HH:MM:SS".
'''
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def Dice(Sides: int = 6) -> int:
'''Roll a dice with a specified number of sides.
Args:
Sides (int): The number of sides on the dice. Default is 6.
Returns:
int: The result of the dice roll.
'''
return random.randint(1, Sides)
def CoinFlip() -> str:
'''Flip a coin and return the result.
Returns:
str: "Heads" or "Tails".
'''
return random.choice(['Heads', 'Tails'])
def Math(Num1: float, Num2: float, Operation: Literal['add', 'subtract', 'multiply', 'divide', 'modulus', 'exponent']) -> float | str:
'''Perform a mathematical operation on two numbers.
Args:
Num1 (float): The first number.
Num2 (float): The second number.
Operation (Literal['add', 'subtract', 'multiply', 'divide', 'modulus', 'exponent']): The operation to perform.
Returns:
float | str: The result of the operation or an error message.
'''
Operations = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y,
'multiply': lambda x, y: x * y,
'divide': lambda x, y: x / y if y != 0 else 'Error: Division by zero',
'modulus': lambda x, y: x % y if y != 0 else 'Error: Division by zero',
'exponent': lambda x, y: x ** y,
}
if Operation in Operations:
return Operations[Operation](Num1, Num2)
else:
return 'Error: Invalid operation'
def TempConversion(Value: float, FromUnit: Literal['Celsius', 'Fahrenheit', 'Kelvin'], ToUnit: Literal['Celsius', 'Fahrenheit', 'Kelvin']) -> float | str:
'''Convert temperature between Celsius, Fahrenheit, and Kelvin.
Args:
Value (float): The temperature value to convert.
FromUnit (Literal['Celsius', 'Fahrenheit', 'Kelvin']): The unit to convert from.
ToUnit (Literal['Celsius', 'Fahrenheit', 'Kelvin']): The unit to convert to.
Returns:
float | str: The converted temperature value or an error message.
'''
if FromUnit == ToUnit:
return Value
if FromUnit == 'Celsius':
if ToUnit == 'Fahrenheit':
return Value * 9/5 + 32
elif ToUnit == 'Kelvin':
return Value + 273.15
elif FromUnit == 'Fahrenheit':
if ToUnit == 'Celsius':
return (Value - 32) * 5/9
elif ToUnit == 'Kelvin':
return (Value - 32) * 5/9 + 273.15
elif FromUnit == 'Kelvin':
if ToUnit == 'Celsius':
return Value - 273.15
elif ToUnit == 'Fahrenheit':
return (Value - 273.15) * 9/5 + 32
return 'Error: Invalid temperature conversion'
def CurrencyConversion(Value: float, FromCurrency: str, ToCurrency: str) -> float | str:
'''Convert currency from one type to another using an online API.
Args:
Value (float): The amount of money to convert.
FromCurrency (str): The currency to convert from (e.g., "USD", "EUR").
ToCurrency (str): The currency to convert to (e.g., "USD", "EUR").
Returns:
float | str: The converted amount or an error message.
'''
Raw = requests.get(f'https://api.frankfurter.dev/v1/latest?base={FromCurrency}&symbols={ToCurrency}')
if Raw.status_code == 200:
Data = Raw.json()
return Data['rates'][ToCurrency] * Value
else:
return 'Error: Currency conversion failed'
def ExecuteCode(Code: str) -> str:
'''
Execute Python code and return the output or error message.
Args:
Code (str): The Python code to execute.
Returns:
str: The output of the executed code or the error message if an exception occurs.
'''
OldStdout = sys.stdout
RedirectedOutput = StringIO()
sys.stdout = RedirectedOutput
try:
Namespace = {}
exec(Code, Namespace, Namespace)
Result = RedirectedOutput.getvalue()
return Result if Result.strip() else 'Code executed successfully (no output).'
except Exception as e:
return f'Error: {str(e)}'
finally:
sys.stdout = OldStdout
def PasswordGenerator(Length: int = 12, IncludeSpecialChars: bool = True, UseDiceware: bool = False) -> str:
'''Generate a random password.
Args:
Length (int): The length of the password to generate. Default is 12.
IncludeSpecialChars (bool): Whether to include special characters in the password. Default is True.
UseDiceware (bool): Whether to use Diceware words for the password. Default is False.
Returns:
str: The generated password.
'''
if UseDiceware:
with open(r'Data/Diceware.txt', 'r', encoding='utf-8') as DicewareFile:
Words = DicewareFile.read().splitlines()
return ' '.join(random.choice(Words) for _ in range(Length))
Characters = string.ascii_letters + string.digits
if IncludeSpecialChars:
Characters += string.punctuation
return ''.join(random.choice(Characters) for _ in range(Length))
def Anagram(Text: str) -> str:
'''Generate an anagram of the input text that is a valid dictionary word.
Args:
Text (str): The input text to generate an anagram from.
Returns:
str: A generated anagram of the input text.
'''
with open(r'Data/Dictionary.txt', 'r', encoding='utf-8') as Database:
Dictionary = set(word.strip().lower() for word in Database if word.strip())
Letters = [Char.lower() for Char in Text if Char.isalpha()]
Anagrams = set(''.join(P) for P in permutations(Letters, len(Letters)))
ValidAnagrams = sorted(word for word in Anagrams if word in Dictionary)
if ValidAnagrams:
return '\n'.join(ValidAnagrams)
else:
return 'No valid anagrams found.'
def Ping(Host: str, Count: int = 8) -> str:
'''Ping a host to check its availability.
Args:
Host (str): The host to ping (e.g., "google.com", "192.168.1.1").
Count (int): The number of ping requests to send. Default is 8.
Returns:
str: The result of the ping command.
'''
if not Host:
return 'Error: Host cannot be empty'
Durations = []
for _ in range(Count):
try:
Start = datetime.datetime.now()
Response = requests.get(f'http://{Host}', timeout=2, headers=Headers)
if Response.status_code != 200:
continue
End = datetime.datetime.now()
Durations.append((End - Start).total_seconds() * 1000)
except requests.RequestException:
Durations.append(None)
if Durations:
Durations = [d for d in Durations if d is not None]
Mean = statistics.mean(Durations)
Median = statistics.median(Durations)
return f'Ping to {Host} successful: {Mean} ms (avg), {Median} ms (median)'
else:
return f'Ping to {Host} failed: No successful responses'
def Purify(Url: str) -> str:
'''Purify HTML content from a URL.
Args:
Url (str): The URL to fetch and purify HTML content from.
Returns:
str: The purified HTML content or an error message.
'''
return PurifyHtml(Url)
# โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
# โ Fun and Entertainment Tools โ
# โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
def Joke(Type: Literal['Any', 'Programming', 'Misc', 'Dark', 'Pun', 'Spooky', 'Christmas']) -> str:
'''Get a random joke.
Args:
Type (Literal['Any', 'Programming', 'Misc', 'Dark', 'Pun', 'Spooky', 'Christmas']): The type of joke to fetch.
Returns:
str: A random joke.
'''
return requests.get(f'https://v2.jokeapi.dev/joke/{Type}?format=txt', headers=Headers).text
def Fact() -> str:
'''Get a random fact.
Returns:
str: A random fact.
'''
return requests.get('https://uselessfacts.jsph.pl/random.json?language=en', headers=Headers).json()['text']
def Plot(GiveExamplePrompt: bool = True) -> list[str]:
'''Generate a random plot for a movie or story.
Args:
GiveExamplePrompt (bool): If True, returns a random plot prompt from a predefined dataset.
Returns:
str: A random plot description.
'''
with open(r'Data/human-writing-dpo.json', 'r', encoding='utf-8') as PlotFile:
Data = json.load(PlotFile)
Plot = random.choice(Data)
Prompt = Plot['prompt']
Chosen = Plot['chosen']
if GiveExamplePrompt:
return [Prompt, Chosen]
else:
return [Prompt, '']
def Trivia(Category: str, Difficulty: str) -> str:
CategoryParam = f'&category={Categories[Category]}' if Category != 'Any Category' else ''
DifficultyParam = f'&difficulty={Difficulties[Difficulty]}' if Difficulty != 'Any Difficulty' else ''
Raw = requests.get(f'https://opentdb.com/api.php?amount=1{CategoryParam}{DifficultyParam}&encode=base64', headers=Headers)
if Raw.status_code == 200:
RawBase64 = Raw.json()
Question = RawBase64['results'][0]['question']
Question = base64.b64decode(Question).decode('utf-8')
CorrectAnswer = base64.b64decode(RawBase64['results'][0]['correct_answer']).decode('utf-8')
IncorrectAnswers = [base64.b64decode(ans).decode('utf-8') for ans in RawBase64['results'][0]['incorrect_answers']]
Options = [CorrectAnswer] + IncorrectAnswers
random.shuffle(Options)
OptionsText = '\n'.join(f'- {Opt}' for Opt in Options)
return f'Trivia Question: {Question}\n\nOptions:\n{OptionsText}\n\nCorrect Answer: {CorrectAnswer}'
else:
return 'Error: Unable to fetch trivia question. Please try again later.'
def Casino(Game: Literal['Roulette', 'Slots'], Input: None | Literal['Red', 'Black', 'Green'], Bet: float) -> str:
'''Generate a random casino game result.
Args:
Game (Literal['Roulette', 'Slots']): The casino game to simulate.
Input (None | Literal['Red', 'Black', 'Green']): The input color for Roulette.
Bet (float): The amount of money to bet.
Returns:
str: A random casino game result.
'''
match Game:
case 'Roulette':
if Input is None:
return 'Place your bet on a color (Red, Black, Green) for Roulette.'
else:
Payout = {
'red': 2,
'black': 2,
'green': 18
}
Wheel = ['green'] + ['red'] * 18 + ['black'] * 18
Result = random.choice(Wheel)
if Result == Input.lower():
return f'You played Roulette and won! ๐ You bet โฌ{Bet} on {Input} and the result was {Result.capitalize()}.\nYou\'ve won โฌ{Bet * Payout[Result]}'
else:
return f'You played Roulette and lost! ๐ข You bet โฌ{Bet} on {Input} and the result was {Result.capitalize()}.'
case 'Slots':
Reels = ['๐', '๐', '๐', '๐', '๐', '๐', 'โญ']
SpinResult = random.choices(Reels, k=3)
Counts = Counter(SpinResult)
MostCommon = Counts.most_common(1)[0]
Symbol, Count = MostCommon
if Count == 3:
if Symbol == 'โญ':
return f'You played Slots and hit the jackpot! ๐ฐ You spun [{" | ".join(SpinResult)}] and won โฌ{Bet * 50}!'
elif Symbol == '๐':
return f'You played Slots and won! ๐ You spun [{" | ".join(SpinResult)}] and won โฌ{Bet * 25}!'
elif Symbol == '๐':
return f'You played Slots and won! ๐ You spun [{" | ".join(SpinResult)}] and won โฌ{Bet * 10}!'
else:
return f'You played Slots and won! ๐ You spun [{" | ".join(SpinResult)}] and won โฌ{Bet * 5}!'
elif Count == 2:
return f'You played Slots and got a pair! ๐ฐ You spun [{" | ".join(SpinResult)}] and won โฌ{Bet * 1.5}!'
else:
return f'You played Slots and lost! ๐ข You spun [{" | ".join(SpinResult)}] and won nothing.'
def EightBall(Question: str) -> str:
'''Ask the Magic 8-Ball a question and get a response.
Args:
Question (str): The question to ask the Magic 8-Ball.
Returns:
str: The response from the Magic 8-Ball.
'''
# Get a random response from the appropriate category
ResponseCategory = random.choices(list(EightBallResponses.keys()), weights=[0.4, 0.2, 0.4])[0]
Response = random.choice(EightBallResponses[ResponseCategory])
return Response
def PigLatin(Text: str) -> str:
'''Convert the input text to Pig Latin.
Args:
Text (str): The text to convert.
Returns:
str: The converted text in Pig Latin.
'''
Words = Text.split()
PigLatinWords = []
for Word in Words:
if Word:
FirstLetter = Word[0].lower()
if FirstLetter in 'aeiou':
PigLatinWord = Word + 'way'
else:
PigLatinWord = Word[1:] + FirstLetter + 'ay'
PigLatinWords.append(PigLatinWord)
return ' '.join(PigLatinWords)
# โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
# โ Text Processing Tools โ
# โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
def Reverse(Text: str) -> str:
'''Reverse the input text.
Args:
Text (str): The text to reverse.
Returns:
str: The reversed text.
'''
return Text[::-1]
def WordCount(Text: str, Choice: Literal['words', 'characters']) -> int:
'''Count the number of words or characters in the input text.
Args:
Text (str): The text to count words in.
Choice (Literal['words', 'characters']): The type of count to perform.
Returns:
int: The number of words in the text.
'''
if Choice == 'words':
return len(Text.split())
elif Choice == 'characters':
return len(Text)
else:
return 0
def Base64(Text: str, Choice: Literal['encode', 'decode']) -> str:
'''Encode or decode text using Base64.
Args:
Text (str): The text to encode or decode.
Choice (Literal['encode', 'decode']): The operation to perform.
- 'encode': Encode the text to Base64.
- 'decode': Decode the Base64 text back to original text.
Returns:
str: The encoded or decoded text.
'''
if Choice == 'encode':
return base64.b64encode(Text.encode()).decode()
elif Choice == 'decode':
return base64.b64decode(Text.encode()).decode()
else:
return 'Error: Invalid choice.'
def Hash(Text: str, Algorithm: Literal['md5', 'sha1', 'sha256', 'sha512']) -> str:
'''Hash the input text using the specified algorithm.
Args:
Text (str): The text to hash.
Algorithm (Literal['md5', 'sha1', 'sha256', 'sha512']): The hashing algorithm to use.
Returns:
str: The resulting hash.
'''
Hashes = {
'md5': hashlib.md5,
'sha1': hashlib.sha1,
'sha256': hashlib.sha256,
'sha512': hashlib.sha512
}
if Algorithm in Hashes:
return Hashes[Algorithm](Text.encode()).hexdigest()
else:
return 'Error: Invalid algorithm.'
# โญโโโโโโโโโโโโโโโโโโโโโฎ
# โ Memory Tools โ
# โฐโโโโโโโโโโโโโโโโโโโโโฏ
def SaveMemory(Text: str, Password: str) -> str:
'''
Save a memory with the given text to MongoDB.
'''
try:
if Collection is None:
return 'Error: MongoDB connection not available'
if Password != MemoryPassword:
return 'Error: Invalid password'
MemoryEntry = {
'text': Text,
'timestamp': datetime.datetime.now()
}
Collection.insert_one(MemoryEntry)
return 'Memory saved successfully'
except Exception as e:
return f'Error: {str(e)}'
def ListMemories(Password: str) -> str:
'''
List all saved memories from MongoDB.
'''
try:
if Collection is None:
return 'Error: MongoDB connection not available'
if Password != MemoryPassword:
return 'Error: Invalid password'
Memories = list(Collection.find().sort('timestamp', -1).limit(50))
if not Memories:
return 'No memories found'
FormattedMemories = []
for Memory in Memories:
Timestamp = Memory['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
MemoryId = str(Memory['_id'])
FormattedMemories.append(f'{MemoryId} [{Timestamp}]: {Memory["text"]}')
return '\n'.join(FormattedMemories)
except Exception as e:
return f'Error: {str(e)}'
def DeleteMemory(MemoryID: str, Password: str) -> str:
'''
Delete a memory by its MongoDB ObjectId.
'''
try:
if Collection is None:
return 'Error: MongoDB connection not available'
if Password != MemoryPassword:
return 'Error: Invalid password'
if not ObjectId.is_valid(MemoryID):
return 'Error: Invalid memory ID format'
Result = Collection.delete_one({'_id': ObjectId(MemoryID)})
if Result.deleted_count > 0:
return 'Memory deleted successfully'
else:
return 'Memory not found'
except Exception as e:
return f'Error: {str(e)}'
def SearchMemories(Query: str, Password: str) -> str:
'''
Search memories by text content.
'''
try:
if Collection is None:
return 'Error: MongoDB connection not available'
if Password != MemoryPassword:
return 'Error: Invalid password'
try:
Collection.create_index([('text', 'text')])
except Exception:
pass
Memories = list(Collection.find(
{'$text': {'$search': Query}}
).sort('timestamp', -1).limit(20))
if not Memories:
return f'No memories found matching "{Query}"'
FormattedMemories = []
for Memory in Memories:
Timestamp = Memory['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
MemoryId = str(Memory['_id'])
FormattedMemories.append(f'{MemoryId} [{Timestamp}]: {Memory["text"]}')
return '\n'.join(FormattedMemories)
except Exception as e:
return f'Error: {str(e)}'
# โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
# โ Gradio Interface Setup โ
# โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
with gradio.Blocks(
title='MCP Utilities ๐ ๏ธ',
theme=Theme
) as App:
gradio.Markdown('''
# MCP Utilities ๐ ๏ธ
A collection of useful tools and utilities for various tasks.
This app provides functionalities like weather information, date and time retrieval, code execution, dice rolling, coin flipping, mathematical operations, pinging hosts, web scraping, jokes, facts, plots, trivia quizzes, casino games and memory management.
''')
with gradio.TabItem('General Tools ๐ ๏ธ'):
with gradio.TabItem('Weather ๐ค๏ธ'):
with gradio.Group():
LocationInput = gradio.Textbox(label='Location ๐', placeholder='Enter a location for weather', lines=1, max_lines=1)
WeatherOutput = gradio.Text(label='Weather โ๏ธ', interactive=False)
WeatherBtn = gradio.Button('Get Weather ๐', variant='primary')
WeatherBtn.click(Weather, inputs=LocationInput, outputs=WeatherOutput)
with gradio.TabItem('Date & Time ๐
'):
with gradio.Group():
DateOutput = gradio.Text(label='Date ๐
', interactive=False)
DateBtn = gradio.Button('Get Date ๐
', variant='primary')
DateBtn.click(Date, outputs=DateOutput)
with gradio.TabItem('Code Execution ๐'):
with gradio.Group():
CodeInput = gradio.Textbox(label='Python Code ๐', placeholder='Enter Python code to execute', lines=5)
CodeOutput = gradio.Text(label='Execution Output ๐', interactive=False)
CodeBtn = gradio.Button('Execute Code โถ๏ธ', variant='primary')
CodeBtn.click(ExecuteCode, inputs=CodeInput, outputs=CodeOutput)
with gradio.TabItem('Password Generator ๐'):
with gradio.Group():
PasswordLength = gradio.Slider(label='Password Length ๐ข', minimum=8, maximum=64, step=1, value=12)
IncludeSpecialChars = gradio.Checkbox(label='Include Special Characters ๐', value=True)
UseDiceware = gradio.Checkbox(label='Generate Diceware Password', value=False, interactive=True)
PasswordOutput = gradio.Text(label='Generated Password ๐', interactive=False)
PasswordBtn = gradio.Button('Generate Password ๐', variant='primary')
PasswordBtn.click(PasswordGenerator, inputs=[PasswordLength, IncludeSpecialChars, UseDiceware], outputs=PasswordOutput)
with gradio.TabItem('Anagram Generator ๐ค'):
with gradio.Group():
AnagramInput = gradio.Textbox(label='Text for Anagram ๐ค', placeholder='Enter text to generate anagram', lines=1, max_lines=1)
AnagramOutput = gradio.Text(label='Generated Anagram ๐ค', interactive=False, max_lines=20)
AnagramBtn = gradio.Button('Generate Anagram ๐ค', variant='primary')
AnagramBtn.click(Anagram, inputs=AnagramInput, outputs=AnagramOutput)
with gradio.TabItem('Dice Roller ๐ฒ'):
with gradio.Group():
DiceSides = gradio.Number(label='Sides of Dice ๐ข', value=6, minimum=1, maximum=100)
DiceOutput = gradio.Text(label='Dice Roll Result ๐ฒ', interactive=False)
DiceBtn = gradio.Button('Roll Dice โป๏ธ', variant='primary')
DiceBtn.click(Dice, inputs=DiceSides, outputs=DiceOutput)
with gradio.TabItem('Coin Flip ๐ช'):
with gradio.Group():
CoinOutput = gradio.Text(label='Coin Flip Result ๐ช', interactive=False)
CoinBtn = gradio.Button('Flip Coin ๐ช', variant='primary')
CoinBtn.click(CoinFlip, outputs=CoinOutput)
with gradio.TabItem('Math Operations โโโ๏ธโ'):
with gradio.Group():
Num1Input = gradio.Number(label='Number 1 1๏ธโฃ', value=0)
Num2Input = gradio.Number(label='Number 2 2๏ธโฃ', value=0)
OperationInput = gradio.Radio(label='Operation ๐ฃ', choices=['add', 'subtract', 'multiply', 'divide', 'modulus', 'exponent'], value='add', interactive=True)
MathOutput = gradio.Text(label='Math Result ๐ฐ', interactive=False)
MathBtn = gradio.Button('Calculate ๐งฎ', variant='primary')
MathBtn.click(Math, inputs=[Num1Input, Num2Input, OperationInput], outputs=MathOutput)
with gradio.TabItem('Temperature Conversion ๐ก๏ธ'):
with gradio.Group():
TempValue = gradio.Number(label='Temperature Value ๐ก๏ธ', value=0)
TempFromUnit = gradio.Radio(label='From Unit ๐', choices=['Celsius', 'Fahrenheit', 'Kelvin'], value='Celsius', interactive=True)
TempToUnit = gradio.Radio(label='To Unit ๐', choices=['Celsius', 'Fahrenheit', 'Kelvin'], value='Celsius', interactive=True)
TempOutput = gradio.Text(label='Converted Temperature ๐ก๏ธ', interactive=False)
TempBtn = gradio.Button('Convert Temperature ๐', variant='primary')
TempBtn.click(TempConversion, inputs=[TempValue, TempFromUnit, TempToUnit], outputs=TempOutput)
with gradio.TabItem('Currency Conversion ๐ฑ'):
with gradio.Group():
CurrencyValue = gradio.Number(label='Amount ๐ฐ', value=1, minimum=0.01, step=0.01)
CurrencyFrom = gradio.Textbox(label='From Currency (e.g., USD) ๐ต', placeholder='Enter currency code', lines=1, max_lines=1)
CurrencyTo = gradio.Textbox(label='To Currency (e.g., EUR) ๐ถ', placeholder='Enter currency code', lines=1, max_lines=1)
CurrencyOutput = gradio.Text(label='Converted Amount ๐ฑ', interactive=False)
CurrencyBtn = gradio.Button('Convert Currency ๐ฑ', variant='primary')
CurrencyBtn.click(CurrencyConversion, inputs=[CurrencyValue, CurrencyFrom, CurrencyTo], outputs=CurrencyOutput)
with gradio.TabItem('Ping Host ๐ก'):
with gradio.Group():
PingInput = gradio.Textbox(label='Host to Ping ๐', placeholder='Enter host (e.g., google.com)', lines=1, max_lines=1)
PingCount = gradio.Number(label='Ping Count ๐ข', value=8, minimum=1, maximum=100)
PingOutput = gradio.Text(label='Ping Result ๐ก', interactive=False)
PingBtn = gradio.Button('Ping Host ๐ก', variant='primary')
PingBtn.click(Ping, inputs=[PingInput, PingCount], outputs=PingOutput)
with gradio.TabItem('Web Scraping ๐'):
with gradio.Group():
PurifyInput = gradio.Textbox(label='URL to Scrape ๐', placeholder='Enter URL to fetch and purify HTML (e.g., https://huggingface.co)', lines=1, max_lines=1)
PurifyOutput = gradio.Text(label='Scraped HTML Content ๐', interactive=False)
PurifyBtn = gradio.Button('Scrape HTML ๐งน (๐ง WIP ๐ง)', variant='primary', interactive=False)
PurifyBtn.click(Purify, inputs=PurifyInput, outputs=PurifyOutput)
with gradio.TabItem('Fun & Entertainment ๐ญ'):
with gradio.TabItem('Random Joke ๐'):
with gradio.Group():
JokeOutput = gradio.Text(label='Random Joke ๐', interactive=False)
JokeType = gradio.Radio(label='Joke Type ๐คก', choices=['Any', 'Programming', 'Misc', 'Dark', 'Pun', 'Spooky', 'Christmas'], value='Any', interactive=True)
JokeBtn = gradio.Button('Get Joke ๐ช', variant='primary')
JokeBtn.click(Joke, inputs=[JokeType], outputs=JokeOutput)
with gradio.TabItem('Random Fact ๐ง '):
with gradio.Group():
FactOutput = gradio.Text(label='Random Fact ๐ง ', interactive=False)
FactBtn = gradio.Button('Get Fact ๐', variant='primary')
FactBtn.click(Fact, outputs=FactOutput)
with gradio.TabItem('Random Plot ๐ฌ'):
with gradio.Group():
PlotOutput = gradio.Text(label='Random Plot ๐ฌ', interactive=False)
PlotExample = gradio.Checkbox(label='Give Example Plot Prompt ๐', value=True, interactive=True)
PlotExampleOutput = gradio.Text(label='Example Plot Prompt ๐', interactive=False)
PlotBtn = gradio.Button('Get Plot ๐ฅ', variant='primary')
PlotBtn.click(Plot, inputs=[PlotExample], outputs=[PlotOutput, PlotExampleOutput])
with gradio.TabItem('Trivia Quiz โ'):
with gradio.Group():
TriviaCategory = gradio.Radio(label='Category ๐ญ', choices=list(Categories.keys()), value='Any Category', interactive=True)
TriviaDifficulty = gradio.Radio(label='Difficulty ๐ฎ', choices=list(Difficulties.keys()), value='Any Difficulty', interactive=True)
TriviaOutput = gradio.Text(label='Trivia Question โ', interactive=False, max_lines=5)
TriviaBtn = gradio.Button('Get Trivia Question ๐', variant='primary')
TriviaBtn.click(Trivia, inputs=[TriviaCategory, TriviaDifficulty], outputs=TriviaOutput)
with gradio.TabItem('Casino Games ๐ฐ'):
with gradio.Group():
CasinoGame = gradio.Radio(label='Casino Game ๐ฒ', choices=['Roulette', 'Slots'], value='Roulette', interactive=True)
CasinoBet = gradio.Slider(label='Bet Amount ๐ฐ', minimum=1, maximum=1000, step=0.5, value=10, interactive=True)
CasinoWheel = gradio.Radio(label='Roulette Color ๐ก', choices=['Red', 'Black', 'Green'], value=None, interactive=True)
CasinoOutput = gradio.Text(label='Casino Result ๐ฐ', interactive=False)
CasinoBtn = gradio.Button('Play Casino ๐ฒ', variant='primary')
CasinoBtn.click(Casino, inputs=[CasinoGame, CasinoWheel, CasinoBet], outputs=CasinoOutput)
with gradio.TabItem('Magic 8-Ball ๐ฎ'):
with gradio.Group():
EightBallInput = gradio.Textbox(label='Ask a Question โ', placeholder='Enter your question for the Magic 8-Ball', lines=1, max_lines=1)
EightBallOutput = gradio.Text(label='Magic 8-Ball Response ๐ฎ', interactive=False)
EightBallBtn = gradio.Button('Ask Magic 8-Ball ๐ฎ', variant='primary')
EightBallBtn.click(EightBall, inputs=EightBallInput, outputs=EightBallOutput)
with gradio.TabItem('Pig Latin Translator ๐ท'):
with gradio.Group():
PigLatinInput = gradio.Textbox(label='Text to Convert to Pig Latin ๐ท', placeholder='Enter text to convert', lines=3)
PigLatinOutput = gradio.Text(label='Pig Latin Translation ๐ท', interactive=False)
PigLatinBtn = gradio.Button('Convert to Pig Latin ๐ท', variant='primary')
PigLatinBtn.click(PigLatin, inputs=PigLatinInput, outputs=PigLatinOutput)
with gradio.TabItem('Text Processing ๐'):
with gradio.TabItem('Text Reversal ๐'):
with gradio.Group():
ReverseInput = gradio.Textbox(label='Text to Reverse ๐', placeholder='Enter text to reverse', lines=3)
ReverseOutput = gradio.Text(label='Reversed Text โฉ๏ธ', interactive=False)
ReverseBtn = gradio.Button('Reverse Text ๐', variant='primary')
ReverseBtn.click(Reverse, inputs=ReverseInput, outputs=ReverseOutput)
with gradio.TabItem('Word Count ๐'):
with gradio.Group():
WordCountInput = gradio.Textbox(label='Text for Word Count ๐', placeholder='Enter text to count words', lines=3)
WordCountChoice = gradio.Radio(label='Count Type ๐ข', choices=['words', 'characters'], value='words', interactive=True)
WordCountOutput = gradio.Text(label='Word Count Result ๐', interactive=False)
WordCountBtn = gradio.Button('Count Words ๐', variant='primary')
WordCountBtn.click(WordCount, inputs=[WordCountInput, WordCountChoice], outputs=WordCountOutput)
with gradio.TabItem('Base64 Encoding/Decoding ๐ฆ'):
with gradio.Group():
Base64Input = gradio.Textbox(label='Text for Base64 ๐ฆ', placeholder='Enter text to encode/decode', lines=3)
Base64Choice = gradio.Radio(label='Operation ๐', choices=['encode', 'decode'], value='encode', interactive=True)
Base64Output = gradio.Text(label='Base64 Result ๐ฆ', interactive=False)
Base64Btn = gradio.Button('Process Base64 ๐ฆ', variant='primary')
Base64Btn.click(Base64, inputs=[Base64Input, Base64Choice], outputs=Base64Output)
with gradio.TabItem('Hashing ๐'):
with gradio.Group():
HashInput = gradio.Textbox(label='Text to Hash ๐', placeholder='Enter text to hash', lines=3)
HashChoice = gradio.Radio(label='Hashing Algorithm ๐', choices=['md5', 'sha1', 'sha256', 'sha512'], value='md5', interactive=True)
HashOutput = gradio.Text(label='Hash Result ๐', interactive=False)
HashBtn = gradio.Button('Generate Hash ๐', variant='primary')
HashBtn.click(Hash, inputs=[HashInput, HashChoice], outputs=HashOutput)
with gradio.TabItem('Memory Tools ๐พ'):
MemoryPasswordInput = gradio.Textbox(label='Password ๐', placeholder='Enter memory password', type='password', lines=1)
with gradio.TabItem('Save Memory ๐พ'):
with gradio.Group():
SaveInput = gradio.Textbox(label='Memory Text ๐ญ', placeholder='Enter text to save', lines=3)
SaveBtn = gradio.Button('Save Memory ๐พ', variant='primary')
SaveBtn.click(SaveMemory, inputs=[SaveInput, MemoryPasswordInput], outputs=gradio.Text(label='Result'))
with gradio.TabItem('Delete Memory ๐๏ธ'):
with gradio.Group():
DeleteInput = gradio.Textbox(label='Memory ID ๐๏ธ', placeholder='Enter ObjectId to delete', lines=1)
DeleteBtn = gradio.Button('Delete Memory ๐๏ธ', variant='secondary')
DeleteBtn.click(DeleteMemory, inputs=[DeleteInput, MemoryPasswordInput], outputs=gradio.Text(label='Result'))
with gradio.TabItem('List Memories ๐'):
with gradio.Group():
ListBtn = gradio.Button('List All Memories ๐', variant='primary')
ListBtn.click(ListMemories, inputs=MemoryPasswordInput, outputs=gradio.Text(label='Memories'))
with gradio.TabItem('Search Memories ๐'):
with gradio.Group():
SearchInput = gradio.Textbox(label='Search Query ๐', placeholder='Enter search text', lines=1)
SearchBtn = gradio.Button('Search Memories ๐', variant='primary')
SearchBtn.click(SearchMemories, inputs=[SearchInput, MemoryPasswordInput], outputs=gradio.Text(label='Results'))
App.launch(
mcp_server=True
) |