Ahmed766 commited on
Commit
b4866d1
·
verified ·
1 Parent(s): 620292e

Upload services/content_studio.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. services/content_studio.py +173 -0
services/content_studio.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional
2
+ from datetime import datetime
3
+ import asyncio
4
+ import logging
5
+ from sqlalchemy.orm import Session
6
+
7
+ from core.ai_gateway import AIGateway, ModelProvider
8
+ from database.models import ContentItem, User
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class ContentStudioService:
13
+ def __init__(self, ai_gateway: AIGateway):
14
+ self.ai_gateway = ai_gateway
15
+
16
+ async def generate_content(
17
+ self,
18
+ topic: str,
19
+ content_type: str,
20
+ platform: str,
21
+ user_id: str,
22
+ db: Session
23
+ ) -> ContentItem:
24
+ """
25
+ Generate content based on topic and requirements
26
+ """
27
+ try:
28
+ # Create initial prompt based on content type and platform
29
+ prompt = self._create_content_prompt(topic, content_type, platform)
30
+
31
+ # Generate content using AI
32
+ generated_content = await self.ai_gateway.generate_text(
33
+ prompt=prompt,
34
+ provider=ModelProvider.LOCAL_LLAMA,
35
+ max_length=1024
36
+ )
37
+
38
+ # Create content item
39
+ content_item = ContentItem(
40
+ owner_id=user_id,
41
+ title=f"{topic[:50]}...",
42
+ content_type=content_type,
43
+ original_prompt=prompt,
44
+ generated_content=generated_content,
45
+ platform_specific_variants={},
46
+ tags=[]
47
+ )
48
+
49
+ # Generate platform-specific variants
50
+ platform_variants = await self._generate_platform_variants(
51
+ generated_content, platform
52
+ )
53
+ content_item.platform_specific_variants = platform_variants
54
+
55
+ # Extract tags and optimize content
56
+ tags = self._extract_tags(generated_content)
57
+ content_item.tags = tags
58
+
59
+ # Save to database
60
+ db.add(content_item)
61
+ db.commit()
62
+ db.refresh(content_item)
63
+
64
+ logger.info(f"Generated content for user {user_id}: {content_item.id}")
65
+ return content_item
66
+
67
+ except Exception as e:
68
+ logger.error(f"Error generating content: {e}")
69
+ db.rollback()
70
+ raise
71
+
72
+ def _create_content_prompt(self, topic: str, content_type: str, platform: str) -> str:
73
+ """
74
+ Create appropriate prompt based on content type and platform
75
+ """
76
+ platform_guidelines = {
77
+ "twitter": "Keep it under 280 characters, use engaging language, include relevant hashtags",
78
+ "instagram": "Focus on visual appeal, use emojis, include call-to-action",
79
+ "youtube": "Create compelling hook in first 15 seconds, include timestamps",
80
+ "blog": "Structure with headings, include SEO keywords, make it scannable"
81
+ }
82
+
83
+ guidelines = platform_guidelines.get(platform, "Make it engaging and platform-appropriate")
84
+
85
+ prompts = {
86
+ "social": f"Create engaging social media content about '{topic}'. {guidelines}.",
87
+ "blog": f"Write a comprehensive blog post about '{topic}'. {guidelines}.",
88
+ "video_script": f"Generate a video script about '{topic}'. {guidelines}.",
89
+ "newsletter": f"Draft newsletter content about '{topic}'. {guidelines}."
90
+ }
91
+
92
+ return prompts.get(content_type, f"Create content about '{topic}' for {platform}. {guidelines}.")
93
+
94
+ async def _generate_platform_variants(
95
+ self,
96
+ original_content: str,
97
+ target_platform: str
98
+ ) -> Dict[str, str]:
99
+ """
100
+ Generate platform-specific content variants
101
+ """
102
+ variants = {}
103
+
104
+ # Generate variants for different platforms
105
+ platforms = ["twitter", "instagram", "linkedin", "facebook", "youtube"]
106
+
107
+ for platform in platforms:
108
+ if platform != target_platform:
109
+ prompt = f"Convert this content for {platform}: {original_content}"
110
+ try:
111
+ variant = await self.ai_gateway.generate_text(
112
+ prompt=prompt,
113
+ max_length=512
114
+ )
115
+ variants[platform] = variant
116
+ except Exception as e:
117
+ logger.warning(f"Could not generate variant for {platform}: {e}")
118
+ variants[platform] = original_content
119
+
120
+ return variants
121
+
122
+ def _extract_tags(self, content: str) -> List[str]:
123
+ """
124
+ Extract tags from content (simplified implementation)
125
+ """
126
+ # In a real implementation, this would use NLP to extract meaningful tags
127
+ words = content.lower().split()
128
+ # Simple heuristic: take the 5 most common words longer than 3 chars
129
+ word_counts = {}
130
+ for word in words:
131
+ clean_word = ''.join(c for c in word if c.isalnum())
132
+ if len(clean_word) > 3:
133
+ word_counts[clean_word] = word_counts.get(clean_word, 0) + 1
134
+
135
+ # Sort by count and return top 5
136
+ sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
137
+ return [word for word, count in sorted_words[:5]]
138
+
139
+ async def optimize_content(
140
+ self,
141
+ content_id: str,
142
+ optimization_type: str,
143
+ db: Session
144
+ ) -> ContentItem:
145
+ """
146
+ Optimize existing content for specific purposes
147
+ """
148
+ content_item = db.query(ContentItem).filter(ContentItem.id == content_id).first()
149
+ if not content_item:
150
+ raise ValueError(f"Content item {content_id} not found")
151
+
152
+ optimization_prompts = {
153
+ "seo": f"Optimize this content for SEO: {content_item.generated_content}",
154
+ "engagement": f"Rewrite this to increase engagement: {content_item.generated_content}",
155
+ "readability": f"Improve readability of this content: {content_item.generated_content}",
156
+ "conversion": f"Optimize this content for conversion: {content_item.generated_content}"
157
+ }
158
+
159
+ if optimization_type not in optimization_prompts:
160
+ raise ValueError(f"Unknown optimization type: {optimization_type}")
161
+
162
+ optimized_content = await self.ai_gateway.generate_text(
163
+ prompt=optimization_prompts[optimization_type],
164
+ max_length=1024
165
+ )
166
+
167
+ content_item.generated_content = optimized_content
168
+ content_item.updated_at = datetime.utcnow()
169
+
170
+ db.commit()
171
+ db.refresh(content_item)
172
+
173
+ return content_item