RafaelAgreda commited on
Commit
37eaae3
·
verified ·
1 Parent(s): f08ae6c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -30
app.py CHANGED
@@ -28,44 +28,56 @@ books_service = build("books", "v1", credentials=credentials)
28
 
29
  # I want to try connect to a google API to get some recommendation of audiobooks!
30
  @tool
31
- def search_audiobooks(topic: str, limit: int = 3) -> list[dict[str, any]]:
32
  """
33
  Search Google Play Books for audiobooks by topic.
34
 
35
  Args:
36
- topic (str): Genre or topic to search (e.g., "epic fantasy").
37
  limit (int): Maximum number of results to return (default: 3).
38
 
39
  Returns:
40
- list[dict[str, any]]: List of audiobook metadata dictionaries.
41
  """
42
- try:
43
- request = books_service.volumes().list(
44
- q=f"subject:{topic}+audiobook",
45
- maxResults=limit,
46
- printType="books",
47
- country="US" # Optional: Restrict to US market
48
- )
49
- response: Dict[str, Any] = request.execute()
50
- audiobooks: List[Dict[str, Any]] = []
51
- for item in response.get("items", []):
52
- volume_info: Dict[str, Any] = item.get("volumeInfo", {})
53
- # Check if audiobook (based on categories or accessInfo)
54
- if "Audiobook" in volume_info.get("categories", []) or volume_info.get("accessInfo", {}).get("epub", {}).get("isAvailable", False):
55
- audiobooks.append({
56
- "title": volume_info.get("title", "Unknown"),
57
- "author": ", ".join(volume_info.get("authors", ["Unknown"])),
58
- "categories": ", ".join(volume_info.get("categories", ["Unknown"])),
59
- "url": volume_info.get("canonicalVolumeLink", "#"),
60
- "estimated_minutes": volume_info.get("pageCount", 180) # Estimate: 1 page ≈ 1 minute
61
- })
62
- return audiobooks
63
- except HttpError as e:
64
- print(f"Google Books API error: {e}")
65
- return []
66
- except Exception as e:
67
- print(f"Unexpected error in search_audiobooks: {e}")
68
- return []
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  @tool
71
  # Function to estimate if audiobook fits time constraint
 
28
 
29
  # I want to try connect to a google API to get some recommendation of audiobooks!
30
  @tool
31
+ def search_audiobooks(topic: str, limit: int = 3) -> List[Dict[str, Any]]:
32
  """
33
  Search Google Play Books for audiobooks by topic.
34
 
35
  Args:
36
+ topic (str): Genre or topic to search (e.g., "science").
37
  limit (int): Maximum number of results to return (default: 3).
38
 
39
  Returns:
40
+ List[Dict[str, Any]]: List of audiobook metadata dictionaries.
41
  """
42
+ audiobooks: List[Dict[str, Any]] = []
43
+ queries: List[str] = [f"{topic}+audiobook", f"subject:{topic}+audiobook"] # Try broader query first
44
+
45
+ for query in queries:
46
+ try:
47
+ request = books_service.volumes().list(
48
+ q=query,
49
+ maxResults=limit,
50
+ printType="books",
51
+ country="US" # Optional: Restrict to US market
52
+ )
53
+ response: Dict[str, Any] = request.execute()
54
+ print(f"API response for query '{query}': {response.get('items', [])}") # Debug output
55
+
56
+ for item in response.get("items", []):
57
+ volume_info: Dict[str, Any] = item.get("volumeInfo", {})
58
+ categories: List[str] = volume_info.get("categories", [])
59
+ # Check if audiobook (based on categories or title/description)
60
+ if any("audiobook" in cat.lower() for cat in categories) or "audiobook" in volume_info.get("title", "").lower():
61
+ audiobooks.append({
62
+ "title": volume_info.get("title", "Unknown"),
63
+ "author": ", ".join(volume_info.get("authors", ["Unknown"])),
64
+ "categories": ", ".join(categories or ["Unknown"]),
65
+ "url": volume_info.get("canonicalVolumeLink", "#"),
66
+ "estimated_minutes": volume_info.get("pageCount", 180) # Estimate: 1 page ≈ 1 minute
67
+ })
68
+ if audiobooks:
69
+ break # Exit if results found
70
+ except HttpError as e:
71
+ print(f"Google Books API error for query '{query}': {e}")
72
+ continue
73
+ except Exception as e:
74
+ print(f"Unexpected error in search_audiobooks for query '{query}': {e}")
75
+ continue
76
+
77
+ if not audiobooks:
78
+ print(f"No audiobooks found for topic: {topic}")
79
+ return audiobooks[:limit] # Ensure no more than limit results
80
+
81
 
82
  @tool
83
  # Function to estimate if audiobook fits time constraint