factorstudios commited on
Commit
e6c8f7e
·
verified ·
1 Parent(s): 8f4fc8b

Update content_gen.py

Browse files
Files changed (1) hide show
  1. content_gen.py +58 -27
content_gen.py CHANGED
@@ -1,7 +1,7 @@
1
  """
2
  content_gen.py — LLM Layer (Local Copy)
3
  Generates a structured manifest from a topic prompt.
4
- API key fetched from environment variables.
5
  """
6
  import json
7
  import re
@@ -13,17 +13,20 @@ from datetime import datetime
13
 
14
  class ContentGenerator:
15
  # API endpoints
16
- OPENROUTER_API_URL = "https://openrouter.ai/api/v1"
 
17
 
18
  def __init__(self, config: Dict[str, Any]):
19
  self.config = config
20
- self.llm_model = config.get("llm_model", "meta-llama/llama-3.3-70b-instruct:free")
21
- self.openrouter_api_key = os.getenv("openrouter_key")
22
- self.openrouter_api_url = self.OPENROUTER_API_URL
 
 
23
  self.scenes_per_video = config.get("scenes_per_video", 7)
24
 
25
- if not self.openrouter_api_key:
26
- raise ValueError("OPENROUTER_KEY environment variable not set")
27
 
28
  def generate_manifest(self, topic: str) -> Dict[str, Any]:
29
  """
@@ -35,12 +38,12 @@ class ContentGenerator:
35
  Returns:
36
  manifest dict with scenes, caption, hashtags
37
  """
38
- print(f"[content] Generating manifest for topic: '{topic}'")
39
 
40
  # Build LLM prompt
41
  prompt = self._build_prompt(topic)
42
 
43
- # Call OpenRouter API
44
  manifest_text = self._call_llm(prompt)
45
 
46
  # Parse JSON from response
@@ -77,9 +80,9 @@ Respond with ONLY valid JSON, no markdown or extra text:
77
  }}"""
78
 
79
  def _call_llm(self, prompt: str) -> str:
80
- """Call the LLM via OpenRouter API."""
81
  headers = {
82
- "Authorization": f"Bearer {self.openrouter_api_key}",
83
  "Content-Type": "application/json",
84
  }
85
 
@@ -97,7 +100,7 @@ Respond with ONLY valid JSON, no markdown or extra text:
97
 
98
  try:
99
  response = requests.post(
100
- f"{self.openrouter_api_url}/chat/completions",
101
  headers=headers,
102
  json=payload,
103
  timeout=60
@@ -113,7 +116,11 @@ Respond with ONLY valid JSON, no markdown or extra text:
113
  if not content:
114
  raise Exception("Empty response from LLM")
115
 
116
- return content
 
 
 
 
117
  except Exception as e:
118
  print(f"[content] ERROR calling LLM: {e}")
119
  raise
@@ -128,29 +135,55 @@ Respond with ONLY valid JSON, no markdown or extra text:
128
  # Try to extract JSON from the response
129
  manifest = json.loads(text)
130
  except json.JSONDecodeError:
131
- # Fallback: create a basic manifest
132
- print(f"[content] WARNING: Could not parse LLM JSON, using fallback manifest")
133
- manifest = self._create_fallback_manifest(topic)
 
 
 
 
 
 
 
 
134
 
135
  # Validate structure
136
  required_keys = ["title", "scenes", "caption", "hashtags"]
137
  for key in required_keys:
138
  if key not in manifest:
139
- raise ValueError(f"Missing key in manifest: {key}")
 
 
140
 
141
  # Ensure exactly scenes_per_video scenes
142
- if len(manifest["scenes"]) != self.scenes_per_video:
143
- print(f"[content] WARNING: Expected {self.scenes_per_video} scenes, got {len(manifest['scenes'])}")
144
- manifest["scenes"] = manifest["scenes"][:self.scenes_per_video]
 
 
 
 
 
 
 
 
145
 
146
  # Ensure each scene has label and image_query
147
- for i, scene in enumerate(manifest["scenes"]):
148
- if "label" not in scene or "image_query" not in scene:
149
- raise ValueError(f"Scene {i} missing 'label' or 'image_query'")
 
 
 
 
 
 
150
 
151
  # Remove emojis from caption and hashtags
152
- manifest["caption"] = self._remove_emojis(manifest["caption"])
153
- manifest["hashtags"] = [self._remove_emojis(tag) for tag in manifest["hashtags"]]
 
 
154
 
155
  # Add timestamp
156
  manifest["timestamp"] = datetime.now().isoformat()
@@ -192,8 +225,6 @@ Respond with ONLY valid JSON, no markdown or extra text:
192
  "\u3030"
193
  "]+", re.UNICODE
194
  )
195
- # Remove emojis and clean up extra spaces
196
  text = emoji_pattern.sub(' ', text)
197
- # Remove multiple spaces
198
  text = re.sub(r'\s+', ' ', text).strip()
199
  return text
 
1
  """
2
  content_gen.py — LLM Layer (Local Copy)
3
  Generates a structured manifest from a topic prompt.
4
+ Updated to use DashScope (Alibaba Cloud) with Qwen3.6-Plus.
5
  """
6
  import json
7
  import re
 
13
 
14
  class ContentGenerator:
15
  # API endpoints
16
+ # Using the international endpoint as it successfully authenticated with the provided key
17
+ DASHSCOPE_API_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
18
 
19
  def __init__(self, config: Dict[str, Any]):
20
  self.config = config
21
+ # Default to qwen3.6-plus as requested
22
+ self.llm_model = config.get("llm_model", "qwen3.6-plus")
23
+ # DashScope API key provided by user
24
+ self.dashscope_api_key = "sk-ws-H.HRRIYI.hUUL.MEUCIQDv1QpE1B2xqwrl2OUSt1o7XbluYkzzaW1sCkp_FMCrewIgSbClEsN--mLhn2JAWt5kyrmaX30grEhaAGcav2TeLS0"
25
+ self.api_url = self.DASHSCOPE_API_URL
26
  self.scenes_per_video = config.get("scenes_per_video", 7)
27
 
28
+ if not self.dashscope_api_key:
29
+ raise ValueError("DashScope API key is not provided")
30
 
31
  def generate_manifest(self, topic: str) -> Dict[str, Any]:
32
  """
 
38
  Returns:
39
  manifest dict with scenes, caption, hashtags
40
  """
41
+ print(f"[content] Generating manifest for topic: '{topic}' using {self.llm_model}")
42
 
43
  # Build LLM prompt
44
  prompt = self._build_prompt(topic)
45
 
46
+ # Call DashScope API
47
  manifest_text = self._call_llm(prompt)
48
 
49
  # Parse JSON from response
 
80
  }}"""
81
 
82
  def _call_llm(self, prompt: str) -> str:
83
+ """Call the LLM via DashScope OpenAI-compatible API."""
84
  headers = {
85
+ "Authorization": f"Bearer {self.dashscope_api_key}",
86
  "Content-Type": "application/json",
87
  }
88
 
 
100
 
101
  try:
102
  response = requests.post(
103
+ f"{self.api_url}/chat/completions",
104
  headers=headers,
105
  json=payload,
106
  timeout=60
 
116
  if not content:
117
  raise Exception("Empty response from LLM")
118
 
119
+ # Remove potential markdown code blocks if the model included them
120
+ content = re.sub(r'^```json\s*', '', content, flags=re.MULTILINE)
121
+ content = re.sub(r'\s*```$', '', content, flags=re.MULTILINE)
122
+
123
+ return content.strip()
124
  except Exception as e:
125
  print(f"[content] ERROR calling LLM: {e}")
126
  raise
 
135
  # Try to extract JSON from the response
136
  manifest = json.loads(text)
137
  except json.JSONDecodeError:
138
+ # Try to find JSON block in case there's still extra text
139
+ json_match = re.search(r'\{.*\}', text, re.DOTALL)
140
+ if json_match:
141
+ try:
142
+ manifest = json.loads(json_match.group())
143
+ except json.JSONDecodeError:
144
+ print(f"[content] WARNING: Could not parse LLM JSON, using fallback manifest")
145
+ return self._create_fallback_manifest(topic)
146
+ else:
147
+ print(f"[content] WARNING: No JSON found in response, using fallback manifest")
148
+ return self._create_fallback_manifest(topic)
149
 
150
  # Validate structure
151
  required_keys = ["title", "scenes", "caption", "hashtags"]
152
  for key in required_keys:
153
  if key not in manifest:
154
+ print(f"[content] WARNING: Missing key '{key}' in manifest")
155
+ fallback = self._create_fallback_manifest(topic)
156
+ manifest[key] = fallback.get(key)
157
 
158
  # Ensure exactly scenes_per_video scenes
159
+ if "scenes" in manifest and isinstance(manifest["scenes"], list):
160
+ if len(manifest["scenes"]) != self.scenes_per_video:
161
+ print(f"[content] WARNING: Expected {self.scenes_per_video} scenes, got {len(manifest['scenes'])}")
162
+ if len(manifest['scenes']) > self.scenes_per_video:
163
+ manifest["scenes"] = manifest["scenes"][:self.scenes_per_video]
164
+ else:
165
+ while len(manifest["scenes"]) < self.scenes_per_video:
166
+ manifest["scenes"].append({
167
+ "label": f"Bonus Tip {len(manifest['scenes'])+1}",
168
+ "image_query": topic
169
+ })
170
 
171
  # Ensure each scene has label and image_query
172
+ if "scenes" in manifest and isinstance(manifest["scenes"], list):
173
+ for i, scene in enumerate(manifest["scenes"]):
174
+ if not isinstance(scene, dict):
175
+ manifest["scenes"][i] = {"label": str(scene), "image_query": topic}
176
+ continue
177
+ if "label" not in scene:
178
+ scene["label"] = f"Scene {i+1}"
179
+ if "image_query" not in scene:
180
+ scene["image_query"] = topic
181
 
182
  # Remove emojis from caption and hashtags
183
+ if "caption" in manifest and isinstance(manifest["caption"], str):
184
+ manifest["caption"] = self._remove_emojis(manifest["caption"])
185
+ if "hashtags" in manifest and isinstance(manifest["hashtags"], list):
186
+ manifest["hashtags"] = [self._remove_emojis(str(tag)) for tag in manifest["hashtags"]]
187
 
188
  # Add timestamp
189
  manifest["timestamp"] = datetime.now().isoformat()
 
225
  "\u3030"
226
  "]+", re.UNICODE
227
  )
 
228
  text = emoji_pattern.sub(' ', text)
 
229
  text = re.sub(r'\s+', ' ', text).strip()
230
  return text