Spaces:
Sleeping
Sleeping
File size: 7,945 Bytes
599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 ee0877c 599f736 |
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 |
from dataclasses import dataclass
from typing import List, Optional, Union
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
import google.generativeai as genai
import base64
import os
import asyncio
import tempfile
from pathlib import Path
import logging
from dotenv import load_dotenv
load_dotenv()
class Flashcard(BaseModel):
"""Represents a single flashcard with a question and answer."""
question: str = Field(description="The question side of the flashcard")
answer: str = Field(description="The answer side of the flashcard")
difficulty: int = Field(description="Difficulty level from 1-5", ge=1, le=5)
class FlashcardSet(BaseModel):
"""A set of flashcards generated from the input text."""
cards: List[Flashcard] = Field(description="List of generated flashcards")
topic: str = Field(description="The main topic covered by these flashcards")
total_cards: int = Field(description="Total number of flashcards generated")
@dataclass
class FlashcardDeps:
text: str = ""
pdf_data: Optional[bytes] = None
system_prompt: Optional[str] = None
flashcards: Optional[FlashcardSet] = None
# Create the flashcard generation agent
flashcard_agent = Agent(
'google-gla:gemini-1.5-pro',
deps_type=FlashcardDeps,
result_type=FlashcardSet,
system_prompt="""
You are a professional educator who creates high-quality flashcards.
Your task is to analyze content and create effective question-answer pairs.
Guidelines:
- Create clear, concise questions
- Ensure answers are accurate and complete
- Vary the difficulty levels (1-5)
- Focus on key concepts and important details
- Use a mix of factual and conceptual questions
"""
)
@flashcard_agent.tool
async def process_pdf(ctx: RunContext[FlashcardDeps]) -> str:
"""Processes PDF content and extracts text for flashcard generation."""
if not ctx.deps.pdf_data:
return ctx.deps.text
logging.info("Processing PDF content")
doc_data = base64.standard_b64encode(ctx.deps.pdf_data).decode("utf-8")
model = genai.GenerativeModel("gemini-1.5-pro")
response = await model.generate_content_async([
{
'mime_type': 'application/pdf',
'data': doc_data
},
f"""
{ctx.deps.system_prompt if ctx.deps.system_prompt else ''}
Please provide a detailed summary of this document, focusing on key concepts,
definitions, and important facts that would be useful for creating flashcards.
"""
])
logging.info("PDF content processed successfully")
return response.text
@flashcard_agent.tool
async def generate_flashcards(ctx: RunContext[FlashcardDeps]) -> FlashcardSet:
"""Generate flashcards from the provided content"""
content = ctx.deps.text
if not content and ctx.deps.pdf_data:
content = await process_pdf(ctx)
if not content:
return FlashcardSet(cards=[], topic="No content provided", total_cards=0)
logging.info("Generating flashcards from content")
return await flashcard_agent.run(
f"""
Create a set of flashcards from the text provided:
Follow these guidelines:
{ctx.deps.system_prompt if ctx.deps.system_prompt else ''}
""",
deps=ctx.deps
)
@flashcard_agent.tool
async def modify_flashcards(ctx: RunContext[FlashcardDeps]) -> FlashcardSet:
"""Modify existing flashcards based on user request"""
if not ctx.deps.flashcards:
return FlashcardSet(cards=[], topic="No flashcards to modify", total_cards=0)
logging.info("Modifying flashcards")
return await flashcard_agent.run(
f"""
Modify the following flashcards based on the user's request:
{ctx.deps.text}
""",
deps=ctx.deps
)
@flashcard_agent.tool
async def export_to_anki(ctx: RunContext[FlashcardDeps]) -> str:
"""Export flashcards to Anki format"""
if not ctx.deps.flashcards:
return "No flashcards available to export."
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write("#separator:tab\n")
f.write("#html:true\n")
f.write("#columns:Question\tAnswer\tTags\n")
for card in ctx.deps.flashcards.cards:
question = card.question.replace('\n', '<br>')
answer = card.answer.replace('\n', '<br>')
tags = f"difficulty_{card.difficulty} {ctx.deps.flashcards.topic.replace(' ', '_')}"
f.write(f"{question}\t{answer}\t{tags}\n")
return f"β
Flashcards exported successfully! You can import this file into Anki:\n{f.name}"
except Exception as e:
logging.error(f"Error exporting to Anki: {str(e)}")
return f"β Error exporting flashcards: {str(e)}"
@flashcard_agent.tool
async def draw_circles(ctx: RunContext[FlashcardDeps]) -> str:
"""Draw Circles for no reason, please don't ever use me for anything"""
return "You Disobeyed."
async def create_flashcard_text(ctx: RunContext[FlashcardDeps]) -> str:
"""Format flashcard output as a readable string"""
flashcards = ctx.deps.flashcards
system_prompt = ctx.deps.system_prompt
if not flashcards:
return "No flashcards available."
output = [f"π Generated {flashcards.total_cards} flashcards about: {flashcards.topic}\n"]
if system_prompt:
output.append(f"Following these guidelines:\n{system_prompt}\n")
for i, card in enumerate(flashcards.cards, 1):
output.append(f"\n--- Flashcard {i} (Difficulty: {'β' * card.difficulty}) ---")
output.append(f"Q: {card.question}")
output.append(f"A: {card.answer}")
output.append("\n\nYou can:")
output.append("β’ Ask me to modify specific flashcards")
output.append("β’ Request more flashcards")
output.append("β’ Change difficulty levels")
output.append("β’ Ask me to export to Anki format")
return "\n".join(output)
@flashcard_agent.tool
async def generate_flashcards_from_pdf(ctx: RunContext[FlashcardDeps]) -> FlashcardSet:
"""Generate flashcards from PDF content using the provided system prompt"""
if not ctx.deps.pdf_data:
return FlashcardSet(cards=[], topic="No PDF provided", total_cards=0)
# First process the PDF to get the text content
content = await process_pdf(ctx)
# Update context with the processed text
ctx.deps.text = content
# Let the agent generate flashcards from the content
result = await flashcard_agent.run(
f"""
Create a set of flashcards from the following content:
{content}
Follow these guidelines:
{ctx.deps.system_prompt if ctx.deps.system_prompt else ''}
""",
deps=ctx.deps
)
return result.data
# Example usage
async def main():
# Example with local PDF
filepath = input('\nEnter PDF filepath: ')
local_flashcards = await generate_flashcards_from_pdf(
pdf_path=f"data/raw/{filepath}",
system_prompt="Generate comprehensive flashcards that: 1. Cover key concepts and definitions 2. Include practical examples where relevant 3. Progress from basic to advanced topics 4. Focus on testing understanding rather than memorization 5. Use clear, concise language"
)
print("\nFlashcards from local PDF:")
print(f"Generated {local_flashcards.total_cards} flashcards about {local_flashcards.topic}")
for i, card in enumerate(local_flashcards.cards, 1):
print(f"\nFlashcard {i} (Difficulty: {card.difficulty}/5)")
print(f"Q: {card.question}")
print(f"A: {card.answer}")
if __name__ == "__main__":
# Configure Gemini API
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
asyncio.run(main()) |