from flask import Flask, request, render_template
import requests
import openai
from bs4 import BeautifulSoup # 追加
openai.api_key = "ENTER-YOUR-API-KEY-HERE"
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# ユーザーから入力されたURLを取得
url = request.form.get('url')
# URLからウェブページの内容を取得
response = requests.get(url)
page_content = response.text
# HTMLタグを取り除く
soup = BeautifulSoup(page_content, 'html.parser')
text_only = soup.get_text()
# ウェブページの内容を日本語に翻訳
prompt_text = "英語から日本語に翻訳:\n" + text_only[:3000] # 最初の3000文字だけ翻訳(APIの制限を考慮)
translation = openai.Completion.create(
model="text-davinci-003",
prompt=prompt_text,
max_tokens=2000,
n=1,
stop=None,
temperature=0.5
)
translated_content = translation.choices[0].text.strip()
# 翻訳結果を表示
return render_template('translated.html', content=translated_content)
# GETリクエストの場合、URLを入力するフォームを表示
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
|