Spaces:
Sleeping
Sleeping
Update content_gen.py
Browse files- 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 |
-
|
| 5 |
"""
|
| 6 |
import json
|
| 7 |
import re
|
|
@@ -13,17 +13,20 @@ from datetime import datetime
|
|
| 13 |
|
| 14 |
class ContentGenerator:
|
| 15 |
# API endpoints
|
| 16 |
-
|
|
|
|
| 17 |
|
| 18 |
def __init__(self, config: Dict[str, Any]):
|
| 19 |
self.config = config
|
| 20 |
-
|
| 21 |
-
self.
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
self.scenes_per_video = config.get("scenes_per_video", 7)
|
| 24 |
|
| 25 |
-
if not self.
|
| 26 |
-
raise ValueError("
|
| 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
|
| 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
|
| 81 |
headers = {
|
| 82 |
-
"Authorization": f"Bearer {self.
|
| 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.
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
#
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
# Validate structure
|
| 136 |
required_keys = ["title", "scenes", "caption", "hashtags"]
|
| 137 |
for key in required_keys:
|
| 138 |
if key not in manifest:
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
|
| 141 |
# Ensure exactly scenes_per_video scenes
|
| 142 |
-
if
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
# Ensure each scene has label and image_query
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
# Remove emojis from caption and hashtags
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
| 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
|