|
import gradio as gr |
|
import pandas as pd |
|
import tempfile |
|
import os |
|
import requests |
|
|
|
|
|
OPENAI_API_KEY = "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" |
|
|
|
def process_csv(csv_file): |
|
|
|
df = pd.read_csv(csv_file.name) |
|
|
|
|
|
outputs = [] |
|
for _, row in df.iterrows(): |
|
id = row['id'] |
|
input_text = row['input'] |
|
|
|
|
|
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}) |
|
|
|
|
|
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) |