-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdescription_generator.py
More file actions
151 lines (124 loc) · 4.91 KB
/
description_generator.py
File metadata and controls
151 lines (124 loc) · 4.91 KB
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
import os
from pathlib import Path
import requests
import json
from typing import Dict, List
import logging
logger = logging.getLogger(__name__)
def generate_mix_description(api_key: str, num_songs: int, genre: str = "lofi jazz") -> Dict[str, str]:
"""Generate a music mix description using Perplexity API"""
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "sonar-pro",
"messages": [
{
"role": "system",
"content": """You are a music channel creator writing YouTube descriptions.
Write in a casual, authentic voice - like a real person sharing their favorite music.
Avoid overly poetic or AI-sounding language.
Keep it simple and genuine, like talking to a friend."""
},
{
"role": "user",
"content": f"""Create a YouTube music mix description package. Use this exact format with spacers:
Thank you for tuning in! :D
[Optional: Add a personal note about the background video/art]
. . . . . . . . . . . . . . . . . . . .
[Write a short, natural description for this {genre} mix. Focus on:
- What makes this mix special
- When/where to listen to it
- Keep it casual and authentic, like a real person wrote it
- Avoid flowery/poetic language
- 2-3 sentences max]
. . . . . . . . . . . . . . . . . . . .
Tags:
[tag1],[tag2],[tag3],... (15 tags max)
. . . . . . . . . . . . . . . . . . . .
Song Titles:
1. [Title 1]
2. [Title 2]
...etc
Important rules for titles:
- Create exactly {num_songs} unique titles
- Each title must be completely different
- No repeating words or themes
- Mix different concepts (nature, urban, emotions, time)
- Keep titles memorable but natural"""
}
],
"max_tokens": 500,
"temperature": 0.9,
"top_p": 0.95,
"presence_penalty": 0.8
}
try:
response = requests.post(
"https://api.perplexity.ai/chat/completions",
headers=headers,
json=payload,
timeout=30
)
if response.status_code != 200:
error_text = response.text
logger.error(f"API Error: {response.status_code} - {error_text}")
return {"success": False, "error": f"API Error: {error_text}"}
response.raise_for_status()
content = response.json()["choices"][0]["message"]["content"]
# Extract song titles
song_titles = extract_song_titles(content)
# Don't save the file here anymore, just return the content
return {
"success": True,
"content": content,
"song_titles": song_titles
}
except requests.exceptions.RequestException as e:
return {"success": False, "error": str(e)}
except Exception as e:
return {"success": False, "error": f"Unexpected error: {str(e)}"}
def extract_song_titles(content: str) -> List[str]:
"""Extract song titles from the API response"""
try:
# Find the song titles section
titles_section = content.split("Song Titles:")[1].strip()
# Split into lines and clean up
titles = []
for line in titles_section.split("\n"):
if line.strip() and ". " in line:
# Remove number and leading/trailing whitespace
title = line.split(". ", 1)[1].strip()
titles.append(title)
return titles
except Exception as e:
logger.error(f"Error extracting song titles: {str(e)}")
return []
def update_description_with_timestamps(description_file: Path, timestamps_file: Path):
"""Update the song titles in the description with timestamps"""
try:
# Read the timestamps
with open(timestamps_file, "r", encoding="utf-8") as f:
timestamps = f.readlines()
# Read the description
with open(description_file, "r", encoding="utf-8") as f:
content = f.read()
# Split content into sections
sections = content.split("\n\n")
# Find the Song Titles section
for i, section in enumerate(sections):
if section.startswith("Song Titles:"):
# Replace the song titles with timestamps
sections[i] = "Tracklist:\n" + "".join(timestamps)
break
# Combine sections back together
updated_content = "\n\n".join(sections)
# Write updated content back to file
with open(description_file, "w", encoding="utf-8") as f:
f.write(updated_content)
logger.info("Successfully updated description with timestamps")
return True
except Exception as e:
logger.error(f"Error updating description with timestamps: {str(e)}")
return False