Rthur2003 commited on
Commit
0867dac
·
1 Parent(s): 0fced84

refactor: Clean up and optimize comment generation logic in Gemini AI Service

Browse files
Files changed (1) hide show
  1. app/routes/commend/gemini_service.py +24 -63
app/routes/commend/gemini_service.py CHANGED
@@ -1,7 +1,4 @@
1
- """
2
- Gemini AI Service for Crown Commend
3
- Token-optimized YouTube comment generation.
4
- """
5
 
6
  from __future__ import annotations
7
 
@@ -37,31 +34,7 @@ def _get_client():
37
  raise ValueError(f"Gemini failed: {e}")
38
 
39
 
40
- def summarize_transcript(transcript_text: str, language: str) -> Tuple[Optional[str], Optional[str]]:
41
- """Transcript özeti - max 2000 karakter input."""
42
- try:
43
- client = _get_client()
44
-
45
- if not transcript_text or len(transcript_text.strip()) < 50:
46
- return None, "No transcript"
47
-
48
- # Token tasarrufu: max 2000 karakter al
49
- text = transcript_text[:2000]
50
-
51
- prompt = f"Summarize in {language}, 1-2 sentences only:\n{text}"
52
-
53
- response = client.models.generate_content(
54
- model="gemini-2.0-flash",
55
- contents=prompt
56
- )
57
- return response.text.strip()[:500], None
58
-
59
- except Exception as e:
60
- logger.error(f"Summary error: {e}")
61
- return None, "Summary failed"
62
-
63
-
64
- # Disclaimer mapping - sabit, prompt'a dahil etmiyoruz
65
  DISCLAIMERS = {
66
  'Turkish': '\n\nNot: Bu yorum AI tarafından üretilmiştir.',
67
  'English': '\n\nNote: This comment was generated by AI.',
@@ -70,7 +43,7 @@ DISCLAIMERS = {
70
  'Japanese': '\n\n注:このコメントはAIによって生成されました。'
71
  }
72
 
73
- # Style mapping - kısa açıklamalar
74
  STYLES = {
75
  'supportive': 'positive, encouraging',
76
  'analytical': 'thoughtful, detailed',
@@ -87,49 +60,39 @@ def generate_comment(
87
  existing_comments: Optional[List[Dict[str, str]]] = None,
88
  transcript_summary: Optional[str] = None
89
  ) -> Tuple[Optional[str], Optional[str]]:
90
- """
91
- Token-optimized comment generation.
92
- ~300-400 tokens input hedefi.
93
- """
94
  try:
95
  client = _get_client()
96
 
97
- # Kısa video bilgisi
98
  title = video_details.get('title', '')[:80]
99
  channel = video_details.get('channelName', '')[:30]
100
- desc = video_details.get('description', '')[:150]
101
- views = video_details.get('viewCount', 0)
102
 
103
- # Sadece en iyi 2 yorum, kısa
104
  comments_text = ""
105
- if existing_comments and len(existing_comments) > 0:
106
- top_comments = existing_comments[:2]
107
- comments_text = " | ".join([c['text'][:80] for c in top_comments])
108
 
109
- # Özet varsa ekle (kısa)
110
- summary_text = ""
111
  if transcript_summary:
112
- summary_text = f"Content: {transcript_summary[:200]}"
113
 
114
- # Stil açıklaması
115
  style_desc = STYLES.get(comment_style, 'natural')
116
 
117
- # Kompakt prompt (~300 token)
118
- prompt = f"""Write a YouTube comment in {language}.
119
 
120
  Video: {title}
121
  Channel: {channel}
122
  {f'Desc: {desc}' if desc else ''}
123
- {f'Views: {views:,}' if views else ''}
124
- {f'Comments: {comments_text}' if comments_text else ''}
125
- {summary_text}
126
 
127
  Style: {style_desc}
128
- Rules:
129
- - 1-2 sentences max
130
- - Sound natural, like a real viewer
131
- - No emojis or minimal (max 1)
132
- - Be specific to video content
133
 
134
  Comment:"""
135
 
@@ -140,23 +103,21 @@ Comment:"""
140
 
141
  generated = response.text.strip()
142
 
143
- # Tırnak temizle
144
  if generated.startswith('"') and generated.endswith('"'):
145
  generated = generated[1:-1]
146
 
147
- # Disclaimer ekle
148
  disclaimer = DISCLAIMERS.get(language, DISCLAIMERS['English'])
149
- final_comment = generated + disclaimer
150
-
151
- return final_comment, None
152
 
153
  except Exception as e:
154
  logger.error(f"Generate error: {e}")
155
- error_str = str(e).lower()
156
 
157
- if "api key" in error_str:
158
  return None, "Invalid API key"
159
- elif "quota" in error_str or "limit" in error_str or "resource" in error_str:
160
  return None, "API quota exceeded"
161
  else:
162
  return None, f"Generation failed: {str(e)}"
 
1
+ """Gemini AI Service for Crown Commend - Token optimized."""
 
 
 
2
 
3
  from __future__ import annotations
4
 
 
34
  raise ValueError(f"Gemini failed: {e}")
35
 
36
 
37
+ # Disclaimer mapping
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  DISCLAIMERS = {
39
  'Turkish': '\n\nNot: Bu yorum AI tarafından üretilmiştir.',
40
  'English': '\n\nNote: This comment was generated by AI.',
 
43
  'Japanese': '\n\n注:このコメントはAIによって生成されました。'
44
  }
45
 
46
+ # Style mapping
47
  STYLES = {
48
  'supportive': 'positive, encouraging',
49
  'analytical': 'thoughtful, detailed',
 
60
  existing_comments: Optional[List[Dict[str, str]]] = None,
61
  transcript_summary: Optional[str] = None
62
  ) -> Tuple[Optional[str], Optional[str]]:
63
+ """Generate YouTube comment with minimal tokens."""
 
 
 
64
  try:
65
  client = _get_client()
66
 
67
+ # Compact video info
68
  title = video_details.get('title', '')[:80]
69
  channel = video_details.get('channelName', '')[:30]
70
+ desc = video_details.get('description', '')[:100]
 
71
 
72
+ # Top 2 comments only
73
  comments_text = ""
74
+ if existing_comments:
75
+ top = existing_comments[:2]
76
+ comments_text = " | ".join([c['text'][:60] for c in top])
77
 
78
+ # Short transcript
79
+ summary = ""
80
  if transcript_summary:
81
+ summary = f"Content: {transcript_summary[:150]}"
82
 
 
83
  style_desc = STYLES.get(comment_style, 'natural')
84
 
85
+ # Minimal prompt (~200 tokens)
86
+ prompt = f"""Write YouTube comment in {language}.
87
 
88
  Video: {title}
89
  Channel: {channel}
90
  {f'Desc: {desc}' if desc else ''}
91
+ {f'Top comments: {comments_text}' if comments_text else ''}
92
+ {summary}
 
93
 
94
  Style: {style_desc}
95
+ Rules: 1-2 sentences, natural, specific to video, max 1 emoji.
 
 
 
 
96
 
97
  Comment:"""
98
 
 
103
 
104
  generated = response.text.strip()
105
 
106
+ # Clean quotes
107
  if generated.startswith('"') and generated.endswith('"'):
108
  generated = generated[1:-1]
109
 
110
+ # Add disclaimer
111
  disclaimer = DISCLAIMERS.get(language, DISCLAIMERS['English'])
112
+ return generated + disclaimer, None
 
 
113
 
114
  except Exception as e:
115
  logger.error(f"Generate error: {e}")
116
+ err = str(e).lower()
117
 
118
+ if "api key" in err:
119
  return None, "Invalid API key"
120
+ elif "quota" in err or "limit" in err or "resource" in err:
121
  return None, "API quota exceeded"
122
  else:
123
  return None, f"Generation failed: {str(e)}"