from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool import requests from bs4 import BeautifulSoup from transformers import pipeline import random import yaml import re from Gradio_UI import GradioUI # Summarization Tool @tool def summarize_text(text: str) -> str: """Summarizes the input text. Args: text: A string containing the content to be summarized. Returns: A string containing the summary of the input text. """ summarizer = pipeline("summarization", model="facebook/bart-large-cnn") summary = summarizer(text, max_length=200, min_length=50, do_sample=False) return summary[0]['summary_text'] # Flashcard Generation Tool @tool def generate_flashcards(summary: str) -> str: """Generates flashcards from a summary. Args: summary: The summarized content to generate flashcards from. Returns: A string containing formatted flashcards. """ sentences = summary.split(".") flashcards = [] # Generate flashcards for sentences that make sense for sentence in sentences: if len(sentence.split()) > 5: # Only take meaningful sentences flashcards.append(f"**Q:** What is the key idea of: _{sentence.strip()}_? **A:** {sentence.strip()}.") # Randomly pick 3 flashcards for variety random_flashcards = random.sample(flashcards, min(3, len(flashcards))) # Format for better readability if random_flashcards: formatted_flashcards = "\n".join(random_flashcards) return f"Here are some flashcards based on the content:\n\n{formatted_flashcards}" else: return "No meaningful flashcards could be generated from the summary." def extract_url(user_input: str) -> str: """Extracts a URL from a user's input text.""" match = re.search(r'https?://\S+', user_input) return match.group(0) if match else None @tool def handle_user_request(user_input: str) -> str: """Processes user input to extract a URL and return a summary with flashcards. Args: user_input: The user's input, which may contain a URL. Returns: A response containing the summary and flashcards, or an error message if no URL is found. """ url = extract_url(user_input) if not url: return "I couldn't find a valid URL in your input. Please provide a direct link." return read_website(url) # Pass only the extracted URL def clean_flashcard_text(flashcard: dict) -> dict: """Cleans newline characters from the flashcard dictionary for keys 'front'/'back' or 'question'/'answer'. Args: flashcard: A dictionary that may contain keys "front" and "back" or "question" and "answer". Returns: A new dictionary with newline characters replaced by a space for the relevant keys. """ cleaned = {} # Determine the key set to clean if "front" in flashcard and "back" in flashcard: keys = ("front", "back") elif "question" in flashcard and "answer" in flashcard: keys = ("question", "answer") else: # Fallback: process all string keys keys = flashcard.keys() for key in keys: value = flashcard.get(key, "") if isinstance(value, str): cleaned[key] = value.replace("\n", " ").strip() else: cleaned[key] = value return cleaned @tool def format_flashcard(flashcard: dict) -> str: """Formats a flashcard dictionary into a readable string. Args: flashcard: A dictionary with either 'front'/'back' or 'question'/'answer' keys. Returns: A formatted string with the cleaned flashcard text. """ cleaned = clean_flashcard_text(flashcard) if "front" in cleaned and "back" in cleaned: return f"**{cleaned['front']}**\n{cleaned['back']}" elif "question" in cleaned and "answer" in cleaned: return f"**Q:** {cleaned['question']}\n**A:** {cleaned['answer']}" else: # Fallback: just output the dictionary as a string return str(cleaned) # Example usage: flashcards = [ {'question': 'What are the 3 types of transformers?', 'answer': 'Encoders, Decoders, Seq2Seq (Encoder–Decoder)'}, {'question': 'What does an encoder-based Transformer do?', 'answer': 'An encoder-based Transformer takes text (or other data) and outputs a dense representation of that text.'} ] formatted_flashcards = "\n\n".join(format_flashcard(fc) for fc in flashcards) print(formatted_flashcards) # Example usage: flashcard = { "front": "There are 3 types of transformers:", "back": "Encoders:\nAn encoder-based Transformer takes text (or other data) as input and outputs a dense representation of that text.\n\nExample: BERT from Google" } formatted_output = format_flashcard(flashcard) print(formatted_output) # Web Scraping Tool (get text content from URL) @tool def read_website(url: str) -> str: """Fetches context from the website and provides a summary and flashcards. Args: url: The URL of the webpage to fetch. Returns: A string containing the summary of the website content and generated flashcards. """ try: # Fetch the webpage response = requests.get(url) # Parse the HTML content soup = BeautifulSoup(response.text, 'html.parser') text_content = soup.get_text(separator=' ', strip=True) # Summarize the website content summary = summarize_text(text_content) # Generate flashcards from the summary flashcards = generate_flashcards(summary) return f"Summary:\n{summary}\n\nFlashcards:\n{flashcards}" except requests.exceptions.RequestException as e: return f"Error fetching the website: {str(e)}" except Exception as e: return f"Error processing the website content: {str(e)}" # Final Answer Tool from tools.final_answer import FinalAnswerTool final_answer = FinalAnswerTool() # Instantiate the model (you may change model settings as needed) model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) # Import tool from Hub (for text-to-image functionality) 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) # Define agent with the tools agent = CodeAgent( model=model, tools=[final_answer, read_website, image_generation_tool, format_flashcard, generate_flashcards, handle_user_request], max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) # Launch the Gradio UI (Hugging Face Spaces automatically handles public links, so no share parameter is needed) GradioUI(agent).launch()