Yasu777 commited on
Commit
f67455f
·
verified ·
1 Parent(s): 9a4eb89

Update article_generator.py

Browse files
Files changed (1) hide show
  1. article_generator.py +59 -50
article_generator.py CHANGED
@@ -58,6 +58,32 @@ def remove_duplicates(text_list):
58
  return result
59
 
60
  # 記事のセクションをGPT-4で拡張する関数
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def expand_section_with_gpt4(h2_text, h3_texts, preloaded_data):
62
  prompts = []
63
  h3_to_text = {}
@@ -134,7 +160,15 @@ def generate_expanded_article(article_html, h3_to_text, cached_responses):
134
  if h3.get_text() in h3_to_text:
135
  new_paragraph = soup.new_tag('p')
136
  new_paragraph.string = h3_to_text[h3.get_text()]
137
- h3.insert_after(new_paragraph)
 
 
 
 
 
 
 
 
138
 
139
  process_summary_section(soup, cached_responses) # まとめセクションを特別処理し、キャッシュされたレスポンスを渡す
140
 
@@ -162,7 +196,7 @@ def setup_plan_and_execute_agent():
162
  # GPT-4を使用してテキストを生成するヘルパー関数
163
  def generate_text_with_gpt4(prompt):
164
  response = openai.ChatCompletion.create(
165
- model="gpt-4o",
166
  messages=[{"role": "system", "content": "以下についての詳細な情報をまとめ、適宜箇所書き、もしくは表を使ってオリジナルの内容にしてください。"},
167
  {"role": "user", "content": prompt}],
168
  temperature=0.7,
@@ -201,30 +235,6 @@ def process_heading(agent, h2_text, h3_for_this_h2, cached_responses):
201
  else:
202
  return (query, "No cached response found for this heading.")
203
 
204
- # IDとセクションを付与する関数
205
- def assign_ids_and_group_sections(html_content):
206
- soup = BeautifulSoup(html_content, 'html.parser')
207
- h2_elements = soup.find_all('h2')
208
- section_id = 1
209
-
210
- for h2 in h2_elements:
211
- section_div = soup.new_tag('div', **{'class': 'section', 'id': f'section-{section_id}'})
212
- h2['id'] = f'h2-{section_id}'
213
- section_div.append(h2.extract())
214
-
215
- next_tag = h2.next_sibling
216
- while next_tag and (next_tag.name != 'h2'):
217
- if next_tag.name == 'h3':
218
- h3_id = f'h3-{section_id}-{next_tag.get_text().split()[0]}'
219
- next_tag['id'] = h3_id
220
- section_div.append(next_tag.extract())
221
- next_tag = next_tag.next_sibling
222
-
223
- h2.insert_before(section_div)
224
- section_id += 1
225
-
226
- return str(soup)
227
-
228
  # 記事を生成する関数
229
  def generate_article(editable_output2):
230
  print("Starting article generation...")
@@ -268,31 +278,32 @@ def generate_article(editable_output2):
268
  research_summary = "\n".join([json.dumps(result) for result in research_results])
269
  instructions = []
270
 
 
271
  instructions.append(f"""
272
- <h1>{h1_text}</h1>
273
- "{h1_text}"に関する導入文を日本語で作成してください。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。""")
274
 
275
  sentences = research_summary.split('。')
276
-
277
- # 質問の数を制限
278
  max_questions_per_h3 = 2
279
 
280
  for idx, h2_text in enumerate(h2_texts):
281
  h3_for_this_h2 = [h3 for h3 in h3_texts if h3.startswith(f"{idx+1}-")]
282
  instructions.append(f"""
283
- <h2>{h2_text}</h2>
284
- "{h2_text}"に関する導入文を日本語で作成してください。この導入文は、以下の小見出しの内容を考慮してください:{"、".join(h3_for_this_h2)}。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。""")
285
- for h3 in h3_for_this_h2:
 
286
  related_sentences = [sentence for sentence in sentences if h3 in sentence][:max_questions_per_h3]
287
  if related_sentences:
288
  content_for_h3 = "。".join(related_sentences) + "。"
289
  instructions.append(f"""
290
- <h3>{h3}</h3>
291
- "{h3}"に関する詳細な内容として、以下の情報を日本語で記述してください:{content_for_h3} ここでも、オリジナルな内容を心がけてください。""")
292
  else:
293
  instructions.append(f"""
294
- <h3>{h3}</h3>
295
- "{h3}"に関する詳細な内容を日本語で記述してください。オリジナルな内容を心がけてください。""")
 
296
 
297
  # トークン数を制限するためにメッセージを分割
298
  split_instructions = []
@@ -335,22 +346,20 @@ def generate_article(editable_output2):
335
  print("Final generated article content:") # 最終的な記事全体の内容を出力
336
  print(final_result)
337
 
338
- # 生成された一時的な記事にIDとグループ化を付与
339
- grouped_html = assign_ids_and_group_sections(final_result)
340
- print("Grouped HTML content:") # グループ化されたHTML内容を表示
341
- print(grouped_html)
342
 
343
- # 重複排除
344
- final_result = remove_duplicates(grouped_html.split('\n'))
 
 
345
 
346
- # 生成された初期記事を拡張
347
- h3_to_text = expand_section_with_gpt4(final_result, h3_texts, cached_responses)
348
- expanded_article = generate_expanded_article("\n".join(final_result), h3_to_text, cached_responses)
349
 
 
350
  with open("output3.txt", "w", encoding="utf-8") as f:
351
- f.write(expanded_article)
352
 
353
  print("Article generation complete. Output saved to output3.txt.")
354
- print(expanded_article) # ログに最終結果を出力
355
-
356
- return expanded_article
 
58
  return result
59
 
60
  # 記事のセクションをGPT-4で拡張する関数
61
+ def expand_h3_sections(soup, preloaded_data):
62
+ h3_elements = soup.find_all('h3')
63
+ for h3 in h3_elements:
64
+ h3_text = h3.get_text(strip=True)
65
+ section_id = h3['id']
66
+ key = f"{h3_text} {section_id}"
67
+
68
+ if key in preloaded_data:
69
+ context = preloaded_data[key]
70
+ prompt = f"「{h3_text}」について詳しく説明してください。こちらが背景情報です:\n{context}"
71
+ else:
72
+ prompt = f"「{h3_text}」について詳しく説明してください。"
73
+
74
+ expanded_text = generate_text_with_gpt4(prompt)
75
+ new_paragraph = soup.new_tag('p')
76
+ new_paragraph.string = expanded_text
77
+
78
+ # h3タグの次の要素を取得し、その後の要素を探す
79
+ next_sibling = h3.find_next_sibling()
80
+ if next_sibling:
81
+ next_sibling.insert_after(new_paragraph) # 次の要素が存在する場合のみ挿入を行う
82
+ else:
83
+ h3.parent.append(new_paragraph) # h3タグの親が存在する場合、親に直接追加
84
+
85
+ return soup
86
+
87
  def expand_section_with_gpt4(h2_text, h3_texts, preloaded_data):
88
  prompts = []
89
  h3_to_text = {}
 
160
  if h3.get_text() in h3_to_text:
161
  new_paragraph = soup.new_tag('p')
162
  new_paragraph.string = h3_to_text[h3.get_text()]
163
+ # h3タグの次の要素を取得し、その後に追加する
164
+ next_sibling = h3.find_next_sibling()
165
+ if next_sibling:
166
+ next_sibling.insert_after(new_paragraph)
167
+ else:
168
+ if h3.parent:
169
+ h3.insert_after(new_paragraph)
170
+ else:
171
+ print(f"Error: h3 element '{h3.get_text()}' has no parent.")
172
 
173
  process_summary_section(soup, cached_responses) # まとめセクションを特別処理し、キャッシュされたレスポンスを渡す
174
 
 
196
  # GPT-4を使用してテキストを生成するヘルパー関数
197
  def generate_text_with_gpt4(prompt):
198
  response = openai.ChatCompletion.create(
199
+ model="gpt-4-turbo",
200
  messages=[{"role": "system", "content": "以下についての詳細な情報をまとめ、適宜箇所書き、もしくは表を使ってオリジナルの内容にしてください。"},
201
  {"role": "user", "content": prompt}],
202
  temperature=0.7,
 
235
  else:
236
  return (query, "No cached response found for this heading.")
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  # 記事を生成する関数
239
  def generate_article(editable_output2):
240
  print("Starting article generation...")
 
278
  research_summary = "\n".join([json.dumps(result) for result in research_results])
279
  instructions = []
280
 
281
+ # IDを含むHTMLプロンプトの作成
282
  instructions.append(f"""
283
+ <h1 id="title">{h1_text}</h1>
284
+ <p>「{h1_text}に関する導入文を日本語で作成してください。直接的なコピーまたは近いフレーズを避けて、オリジナルな内容にしてください。</p>""")
285
 
286
  sentences = research_summary.split('。')
 
 
287
  max_questions_per_h3 = 2
288
 
289
  for idx, h2_text in enumerate(h2_texts):
290
  h3_for_this_h2 = [h3 for h3 in h3_texts if h3.startswith(f"{idx+1}-")]
291
  instructions.append(f"""
292
+ <div id="section-{idx+1}">
293
+ <h2 id="h2-{idx+1}">{h2_text}</h2>
294
+ <p>「{h2_text}」に関する導入文を日本語で作成してください。この導入文は、以下の小見出しの内容を考慮してください:{"、".join(h3_for_this_h2)}。</p>""")
295
+ for h3_idx, h3 in enumerate(h3_for_this_h2):
296
  related_sentences = [sentence for sentence in sentences if h3 in sentence][:max_questions_per_h3]
297
  if related_sentences:
298
  content_for_h3 = "。".join(related_sentences) + "。"
299
  instructions.append(f"""
300
+ <h3 id="h3-{idx+1}-{h3_idx+1}">{h3}</h3>
301
+ <p>「{h3}に関する詳細な内容として、以下の情報を日本語で記述してください:{content_for_h3}</p>""")
302
  else:
303
  instructions.append(f"""
304
+ <h3 id="h3-{idx+1}-{h3_idx+1}">{h3}</h3>
305
+ <p>「{h3}に関する詳細な内容を日本語で記述してください。オリジナルな内容を心がけてください。</p>""")
306
+ instructions.append("</div>") # 各セクションの終わりにdivタグを閉じる
307
 
308
  # トークン数を制限するためにメッセージを分割
309
  split_instructions = []
 
346
  print("Final generated article content:") # 最終的な記事全体の内容を出力
347
  print(final_result)
348
 
349
+ # 更新されたHTMLの解析
350
+ updated_soup = BeautifulSoup(final_result, 'html.parser')
 
 
351
 
352
+ # 初期データTavily検索で収集する関数
353
+ h3_texts = [h3.get_text(strip=True) for h3 in updated_soup.find_all('h3')]
354
+ cached_responses = perform_initial_tavily_search([], h3_texts)
355
+ save_preloaded_tavily_data(cached_responses)
356
 
357
+ # h3タグの拡張を行う
358
+ expanded_soup = expand_h3_sections(updated_soup, cached_responses)
 
359
 
360
+ final_html = str(expanded_soup)
361
  with open("output3.txt", "w", encoding="utf-8") as f:
362
+ f.write(final_html)
363
 
364
  print("Article generation complete. Output saved to output3.txt.")
365
+ return final_html