如何申請openAI API金鑰:https://hackmd.io/@flagmaker/BJuxF7bkye
第一次用的話,可能要在電腦內建的cmd裡面先跑過pip install XXX(各種等等python要import的東西,我沒學過程式所以我也講不清楚。總之各位如果python出現error,可以直接整段複製丟chatGPT問他怎麼辦xd)
以下是要貼上python的東東,openAI API金鑰跟文本記得改成你自己的內容。
import openai
import os
from docx import Document
from docx.shared import Pt
# 在這裡輸入你的 OpenAI API 金鑰
api_key = 'your-api-key-here'
def refine_text(segment, model="gpt-3.5-turbo-1106"):
try:
client = openai.OpenAI(api_key=api_key) # 初始化 client 並傳遞 API 金鑰
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a professional text editor. Please refine the following Chinese text to make it more fluent and natural without changing its meaning."},
{"role": "user", "content": f"請潤色以下中文內容,使其更加通順自然:\\n\\n{segment}"}
]
)
return response.choices[0].message.content
except Exception as e:
print("Error during text refinement:", e)
return segment # 若發生錯誤,則返回原始文本
def merge_sentences(text, max_length=600):
lines = text.split('\\n') # 逐行分割文本
paragraphs = []
paragraph = ""
for line in lines:
line = line.strip()
if not line: # 遇到空行則視為段落結束
if paragraph:
paragraphs.append(paragraph)
paragraph = ""
else:
if len(paragraph) + len(line) < max_length:
paragraph += (" " if paragraph else "") + line
else:
paragraphs.append(paragraph)
paragraph = line
if paragraph: # 處理最後的段落
paragraphs.append(paragraph)
# 使用 AI 潤色每個段落
refined_paragraphs = [refine_text(p) for p in paragraphs]
return "\\n\\n".join(refined_paragraphs).strip()
# 你的逐字稿文本
transcript_text = '''
這是一段測試文本。
它被切成很多行。
這樣閱讀起來比較困難。
這是另一個段落。
它也被切開了。
需要重新整理成適當的段落。
'''
# 整理並潤色文本
merged_text = merge_sentences(transcript_text)
print(merged_text)
# 創建 Word 文件
doc = Document()
doc.add_heading('整理後的逐字稿', 0)
doc.add_paragraph(merged_text)
# 儲存文件
file_path = 'merged_transcript.docx'
doc.save(file_path)
# 查看當前工作目錄
current_directory = os.getcwd()
print(f"當前工作目錄是: {current_directory}")