File size: 6,005 Bytes
8a302ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

from fastapi import Request, FastAPI, BackgroundTasks
import gspread
import requests
import openai

# OpenAI API KEY
API_KEY = "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"
openai.api_key = API_KEY


# Chatbase API๋ฅผ ์ด์šฉํ•ด ํ…์ŠคํŠธ๋ฅผ ๋ณด๋‚ด๊ณ  ์‘๋‹ต์„ ๋ฐ›๋Š” ํ•จ์ˆ˜
def getResponseFromChatbase(prompt):
    url = "https://www.chatbase.co/api/v1/chat"
    payload = {
        "stream": False,
        "temperature": 0,
        "chatId": "6dMpdT5zPPS5ik9pKptsH",
        "messages": [{"role": "user", "content": prompt}]
    }
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "authorization": "Bearer e81b355c-30cc-47ca-b9fa-deb33f7159ad"
    }
    response = requests.post(url, json=payload, headers=headers)
    # Chatbase API ์‘๋‹ต์˜ ํ˜•ํƒœ์— ๋”ฐ๋ผ ์ ์ ˆํ•œ ํ•„๋“œ๋ฅผ ๋ฐ˜ํ™˜
    # {"text":"์•ˆ๋…•ํ•˜์„ธ์š”! ์ด๋‚˜๋ผ๋„์›€ AI์ž…๋‹ˆ๋‹ค. ์–ด๋–ค ๋„์›€์ด ํ•„์š”ํ•˜์‹ ๊ฐ€์š”?"}
    return response.json()['text']


def getResponseFromGooey(prompt):
    url = "https://api.gooey.ai/v2/TextToSpeech/"
    gooey_key = 'sk-lbYNmTYKFA7Fb0yP60QsB5huMHjBmyRAJ0kJeFZMdgifeAEN'
    payload = {
        "text_prompt": prompt,
        "tts_provider": "ELEVEN_LABS",
        "uberduck_voice_name": "the-rock",
        "uberduck_speaking_rate": 1,
        "google_voice_name": "en-IN-Wavenet-A",
        "google_speaking_rate": 1,
        "google_pitch": 0,
        "bark_history_prompt": "en_speaker_0",
        "elevenlabs_voice_name": None,
        "elevenlabs_api_key": "c5fb99a2b25402f104d246379bcf819a",
        "elevenlabs_voice_id": "SKwm0HLYsVDCM2ruvw2p",
        "elevenlabs_model": "eleven_multilingual_v2",
        "elevenlabs_stability": 0.5,
        "elevenlabs_similarity_boost": 0.75,
        "elevenlabs_style": 0,
        "elevenlabs_speaker_boost": True,
    }
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "authorization": "Bearer " + gooey_key
    }
    response = requests.post(url, json=payload, headers=headers)
    return response.json()['output']['audio_url']


# ๋ฉ”์„ธ์ง€ ์ „์†ก์„ ์œ„ํ•œ ํฌ๋งท ํ•จ์ˆ˜
def textResponseFormatKakao(bot_response):
    response = {
        'version': '2.0',
        'template': {
            'outputs': [{"simpleText": {"text": bot_response}}],
            'quickReplies': []
        }
    }
    return response


# ChatGPT์—๊ฒŒ ์งˆ๋ฌธ/๋‹ต๋ณ€ ๋ฐ›๊ธฐ
def getTextFromGPT(prompt):
    text = 'You are a thoughtful assistant.'\
           ' Respond to all input in 25 words and answer in korean.'
    messages_prompt = [{
        "role": "system",
        "content": text
    }]
    messages_prompt += [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                            messages=messages_prompt)
    message = response["choices"][0]["message"]["content"]
    return message


def create_callback_request_kakao(prompt, serverType, callbackUrl):
    if serverType == 'CHAT':
        # OpenAI API/Chatbase ๋กœ prompt๋ฅผ ๋˜์ ธ์„œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„์˜ต๋‹ˆ๋‹ค.
        bot_res = getResponseFromChatbase(prompt)
    elif serverType == 'AUDIO':
        # Gooey๋กœ prompt๋ฅผ ๋˜์ ธ์„œ ์˜ค๋””์˜ค ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ๋ฐ›์•„์˜ต๋‹ˆ๋‹ค.
        bot_res = getResponseFromGooey(prompt)

    # callbackUrl๋กœ ๊ฒฐ๊ณผ๊ฐ’์„ post๋ฐฉ์‹์œผ๋กœ ์ „์†กํ•ฉ๋‹ˆ๋‹ค.
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    requests.post(
        callbackUrl,
        json=textResponseFormatKakao(bot_res),
        headers=headers,
        timeout=5
    )
    return ""


# FastAPI ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
app = FastAPI()


# ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ฒ˜๋ฆฌ: verymuchmorethanastronomically.tistory.com/18 ์ฐธ๊ณ .
@app.post("/chat2/", tags=["kakao"])
async def chat2(request: Request, background_tasks: BackgroundTasks,):
    # await ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š์œผ๋ฉด userRequest๋ฅผ ์ฝ๋‹ค๊ฐ€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒ๋ฉ๋‹ˆ๋‹ค.
    kakao_request = await request.json()

    # /ask, /img, /gs ์ฒ˜๋ฆฌ.
    if '/gs' in kakao_request["userRequest"]["utterance"]:
        question = kakao_request["userRequest"]["utterance"].replace("/gs", "")
        # json ํŒŒ์ผ์ด ์œ„์น˜ํ•œ ๊ฒฝ๋กœ๋ฅผ ๊ฐ’์œผ๋กœ ์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค.
        json_file_path = "botree-404708-b377977f1aa4.json"
        gc = gspread.service_account(json_file_path)
        sheet = 'https://docs.google.com/spreadsheets/d/'\
                '1Iq5N59xU725bmxas730B_UQYZvX4EK_0rnRL-egxl_I/edit?usp=sharing'
        doc = gc.open_by_url(sheet)
        worksheet = doc.worksheet("์‹œํŠธ1")

        # ์ด์ „์— ์ž…๋ ฅ๋œ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ ๋งˆ์ง€๋ง‰ ํ–‰์„ ์ฐพ์•„์„œ ๋‹ค์Œ ํ–‰์— ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”๊ฐ€
        last_row = len(worksheet.col_values(1)) + 1
        cell = f'A{last_row}'

        # ์‚ฌ์šฉ์ž๊ฐ€ ์ฑ—๋ด‡์— ์ž…๋ ฅํ•œ ๊ฐ’์„ ํ•ด๋‹น ์—ด์— ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.
        worksheet.update(cell, question)
        return textResponseFormatKakao(f"{cell}์— ์ž‘์„ฑ ์™„๋ฃŒ.")
    elif '/sp' in kakao_request["userRequest"]["utterance"]:
        prompt = kakao_request["userRequest"]["utterance"].replace("/sp", "")
        type = 'AUDIO'
    elif 'ask' in kakao_request['userRequest']['utterance']:
        prompt = kakao_request["userRequest"]["utterance"].replace("/ask", "")
        type = 'CHAT'

    # ํ…์ŠคํŠธ์˜ ๊ธธ์ด๊ฐ€ 10์ž ์ด์ƒ 200์ž ์ดํ•˜์ธ์ง€ ํ™•์ธ
    length = len(kakao_request["userRequest"]["utterance"])
    if length < 5 or length > 200:
        return textResponseFormatKakao("์งˆ๋ฌธ์€ 5์ž ์ด์ƒ 200์ž ์ดํ•˜๋กœ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”")

    # ๋ฐฑ๊ทธ๋ผ์šด๋“œ๋กœ ์นด์นด์˜ค ์ฑ—๋ด‡์—๊ฒŒ ์‘๋‹ต์„ ๋ณด๋ƒ…๋‹ˆ๋‹ค.
    background_tasks.add_task(
        create_callback_request_kakao,
        prompt=prompt,
        serverType=type,
        callbackUrl=kakao_request["userRequest"]["callbackUrl"],
    )

    # user_requests[user_id] += 1
    # useCallback์„ true์ฒ˜๋ฆฌํ•ด์ค˜์•ผ ์นด์นด์˜ค์—์„œ 1๋ถ„๊ฐ„ callbackUrl์„ ์œ ํšจํ™”์‹œํ‚ต๋‹ˆ๋‹ค.
    return {"version": "2.0", "useCallback": True}