Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool, OpenAIServerModel | |
| import datetime | |
| import requests | |
| import pytz | |
| import base64 | |
| import yaml | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| from typing import List, Tuple | |
| import os | |
| momo_key = os.getenv("MomoKey") | |
| # Below is an example of a tool that does nothing. Amaze us with your creativity ! | |
| def my_custom_tool(arg1:str, arg2:int)-> str: | |
| """A tool that does nothing yet. | |
| Args: | |
| arg1: the first argument | |
| arg2: the second argument | |
| """ | |
| return "What magic will you build ?" | |
| def get_sura(sura_number: int) -> str: | |
| """A tool that gets the text of a sura based on its sura number | |
| Args: | |
| sura_number: The sura number of the sura. | |
| """ | |
| url = f"https://quran-challenge.com/app/php/getverses.php?sura_number={sura_number}" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| data = response.json() | |
| result = "" | |
| for verse in data: | |
| nr = verse['nr'] | |
| text = verse['tanzil_text'] | |
| result += f"{nr}: {text}\n" | |
| return f"The text of the sura {sura_number} is:\n {result}" | |
| else: | |
| return "Error: Could not fetch the sura data." | |
| def search_quran(search_type: str, search_value: str) -> str: | |
| """A tool that searches for a given term in the Quran based on the specified search type. The spellingspecial search type indicates the othmani original spelling of the text. | |
| Args: | |
| search_type: The type of search (e.g., 'word', 'root', 'spellingspecial', 'verbvorm'). | |
| search_value: The term to be searched for in the Quran. | |
| Returns: | |
| a complete list of the verses found. Each line starts with sura number followed by : followed by verse number followed by a space and then finally the verse text. | |
| """ | |
| valid_search_types = {"word", "root", "spellingspecial", "verb_form"} | |
| if search_type not in valid_search_types: | |
| return f"Error: Invalid search type '{search_type}'. Valid options are: {', '.join(valid_search_types)}." | |
| url = f"https://quran-challenge.com/app/php/search.php?query={search_type}:{search_value}" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| data = response.json() | |
| result = "" | |
| if "result" in data: | |
| for verse in data["result"]: | |
| sura = verse['sura'] | |
| nr = verse["nr"] | |
| text = verse["tanzil_text"] | |
| result += f"{sura}:{nr} {text}\n" | |
| return f"The term '{search_value}' under search type '{search_type}' is found in the following verses:\n{result}" | |
| else: | |
| return f"No results found for '{search_value}' under search type '{search_type}'." | |
| else: | |
| return "Error: Could not fetch data from the Quran API." | |
| def search_quran_advanced(search_terms: list, operator: str = "VAND") -> str: | |
| """A tool that searches for multiple terms in the same verse in the Quran using AND/OR conditions. | |
| The AND condition is named: VAND and the OR condition is named VOR. The prefix V stands for "Verse", where the search happens on verse level. | |
| Args: | |
| search_terms: A list of tuples where each tuple contains a search type (e.g., 'word', 'root') and the corresponding term to search. | |
| operator: The logical operator to combine conditions ('VAND' or 'VOR'). | |
| Returns: | |
| A complete list of the verses found. Each line starts with sura number followed by : followed by verse number followed by a space and then finally the verse text. | |
| Example: | |
| search_quran_advanced([('word', 'مجمع'), ('word', 'البحرين')], 'VAND') | |
| """ | |
| valid_search_types = {"word", "root", "spellingspecial", "verb_form"} | |
| valid_operators = {"VAND", "VOR"} | |
| if operator not in valid_operators: | |
| return f"Error: Invalid operator '{operator}'. Valid options are: {', '.join(valid_operators)}." | |
| # Validate search terms | |
| filters = [] | |
| for search_type, search_value in search_terms: | |
| if search_type not in valid_search_types: | |
| return f"Error: Invalid search type '{search_type}'. Valid options are: {', '.join(valid_search_types)}." | |
| filters.append(f"{search_type}:{search_value}") | |
| query_string = f"{operator}".join(filters) | |
| url = f"https://quran-challenge.com/app/php/search.php?query={query_string}" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| data = response.json() | |
| result = "" | |
| if "result" in data: | |
| for verse in data["result"]: | |
| sura = verse['sura'] | |
| nr = verse["nr"] | |
| text = verse["tanzil_text"] | |
| result += f"{sura}:{nr} {text}\n" | |
| return f"Search results for {query_string}:\n{result}" | |
| else: | |
| return f"No results found for '{query_string}'." | |
| else: | |
| return "Error: Could not fetch data from the Quran API." | |
| from typing import List, Tuple | |
| def abjad_value(sura: int, verse: int) -> Tuple[List[int], int]: | |
| """A tool that calculates the Abjad values (Gematrical values) of Arabic letters in a given text and returns a tuple containing: | |
| - A list of individual Abjad values for each letter in the text. | |
| - The total Abjad value for the entire text. | |
| Args: | |
| sura: The number of the Sura in the Quran. | |
| verse: The number of the verse in the given Sura. | |
| Returns: | |
| tuple: A tuple containing two elements: | |
| 1. A list of integers representing the Abjad value for each letter in the text. | |
| 2. An integer representing the total Abjad value of the entire text. | |
| Example: | |
| abjad_value(1, 1) | |
| Returns: | |
| ([2, 60, 40, 1, 30, 30, 5, 1, 30, 200, 8, 40, 50, 1, 30, 200, 8, 10, 40], 786) | |
| """ | |
| abjad_dict = { | |
| 'ا': 1, 'أ': 1, 'إ': 1, 'آ': 1, 'ء': 1, | |
| 'ب': 2, 'ت': 400, 'ث': 500, 'ج': 3, 'ح': 8, 'خ': 600, | |
| 'د': 4, 'ذ': 700, 'ر': 200, 'ز': 7, 'س': 60, 'ش': 300, | |
| 'ص': 90, 'ض': 800, 'ط': 9, 'ظ': 900, 'ع': 70, 'غ': 1000, | |
| 'ف': 80, 'ق': 100, 'ك': 20, 'ل': 30, 'م': 40, 'ن': 50, | |
| 'ه': 5, 'و': 6, 'ى': 10, 'ي': 10, 'ئ': 10, 'ؤ': 6, 'ة': 5 | |
| } | |
| expression = '' | |
| url = f"https://quran-challenge.com/app/php/getverse.php?sura_number={sura}&verse_number={verse}" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| data = response.json() | |
| result = "" | |
| for verse in data: | |
| nr = verse['nr'] | |
| text = verse['text'] | |
| expression = f"{text}" | |
| expression = expression.replace(" ", "") # Remove spaces from the expression | |
| individual_values = [] | |
| total_value = 0 | |
| for letter in expression: | |
| if letter in abjad_dict: | |
| value = abjad_dict[letter] | |
| individual_values.append(value) | |
| total_value += value | |
| return individual_values, total_value | |
| def calculate_expenses(sallery: int) -> str: | |
| """A tool that calculate the expenses of a given sallery. | |
| Args: | |
| sallery: The given sallery. | |
| """ | |
| return f"the expenses of the sallery {sallery} are: {sallery * 0.82 + (sallery * (0.03))} CHF." | |
| def encode_text(text: str) -> str: | |
| """Encodes text using XOR with a key and Base64 encoding. | |
| Args: | |
| text: The text to encode. | |
| Returns: | |
| Encoded Base64 string. | |
| """ | |
| key_cycle = (ord(k) for k in momo_key) # Cycle through key chars | |
| encoded_bytes = bytes([ord(c) ^ next(key_cycle) for c in text]) # XOR each char | |
| return base64.b64encode(encoded_bytes).decode() | |
| def decode_text(encoded_text: str) -> str: | |
| """Decodes a Base64-encoded XOR encrypted text using the given key. | |
| Args: | |
| encoded_text: The encoded Base64 string. | |
| Returns: | |
| Decoded plain text. | |
| """ | |
| key_cycle = (ord(k) for k in momo_key) | |
| decoded_bytes = base64.b64decode(encoded_text) # Decode Base64 | |
| return ''.join(chr(b ^ next(key_cycle)) for b in decoded_bytes) | |
| def get_current_time_in_timezone(timezone: str) -> str: | |
| """A tool that fetches the current local time in a specified timezone. | |
| Args: | |
| timezone: A string representing a valid timezone (e.g., 'America/New_York'). | |
| """ | |
| try: | |
| # Create timezone object | |
| tz = pytz.timezone(timezone) | |
| # Get current time in that timezone | |
| local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") | |
| return f"The current local time in {timezone} is: {local_time}" | |
| except Exception as e: | |
| return f"Error fetching time for timezone '{timezone}': {str(e)}" | |
| final_answer = FinalAnswerTool() | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud', #meta-llama/Meta-Llama-3-8B-Instruct | |
| custom_role_conversions=None, | |
| ) | |
| """ | |
| model = OpenAIServerModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id="gpt-4o-mini", | |
| api_key= api_key, | |
| custom_role_conversions=None, | |
| ) | |
| """ | |
| # Import tool from Hub | |
| image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| with open("prompts.yaml", 'r') as stream: | |
| prompt_templates = yaml.safe_load(stream) | |
| agent = CodeAgent( | |
| model=model, | |
| tools=[final_answer, calculate_expenses, image_generation_tool, encode_text, decode_text, get_sura, search_quran, search_quran_advanced, abjad_value], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() | |