risdom / app.py
yosuke-i's picture
Update app.py
d9500e2 verified
raw
history blame
1.77 kB
import gradio as gr
import pandas as pd
import tempfile
import os
import requests
# OpenAI API キーを設定する
OPENAI_API_KEY = "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" # ここにあなたのOpenAI API キーを入力してください
def process_csv(csv_file):
# CSVファイルを読み込む
df = pd.read_csv(csv_file.name)
# ChatGPT API に入力を送信し、出力を取得
outputs = []
for _, row in df.iterrows():
id = row['id']
input_text = row['input']
# ChatGPT API を直接呼び出す
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
data = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": input_text}]
}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
response_json = response.json()
output_text = response_json["choices"][0]["message"]["content"]
outputs.append({'id': id, 'output': output_text})
# 出力をCSVファイルに書き込む
output_df = pd.DataFrame(outputs)
with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as tmp:
output_df.to_csv(tmp.name, index=False)
output_path = tmp.name
# ファイル名を変更
new_path = os.path.join(os.path.dirname(output_path), "output.csv")
os.rename(output_path, new_path)
return new_path
interface = gr.Interface(
fn=process_csv,
inputs=gr.File(label="CSVファイルをアップロード"),
outputs=gr.File(label="ダウンロード", file_count="singular"),
allow_flagging="never",
)
interface.launch(share=True)