File size: 1,510 Bytes
06a4f42
 
 
 
 
 
 
 
 
 
 
3274df2
 
 
 
 
 
 
 
 
 
 
06a4f42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import logging
import os

from .utils import timeit

import openai

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)


def set_openai_key(openai_api_key_textbox = None):
    log.info(f"Setting OpenAI key.")
    if openai_api_key_textbox is not None:
        os.environ["OPENAI_API_KEY"] = openai_api_key_textbox
    try:
        openai.api_key = os.getenv("OPENAI_API_KEY")
    except KeyError as e:
        log.warning("OPENAI_API_KEY not found in environment variables.")
        pass

set_openai_key()

@timeit
def speech_to_text(audio_path):
    log.info("Transcribing audio...")
    transcript = openai.Audio.transcribe("whisper-1", open(audio_path, "rb"))
    text = transcript["text"]
    log.info(f"Transcript: \n\t{text}")
    return text


@timeit
def top_response(prompt, system=None, model="gpt-3.5-turbo", max_tokens=20, temperature=0.8):
    _prompt = [
        {
            "role": "user",
            "content": prompt,
        },
    ]
    if system:
        _prompt = [
            {
                "role": "system",
                "content": system,
            },
        ] + _prompt
    log.info(f"API call to {model} with prompt: \n\n\t{_prompt}\n\n")
    _response = openai.ChatCompletion.create(
        model=model,
        messages=_prompt,
        temperature=temperature,
        n=1,
        max_tokens=max_tokens,
    )
    log.info(f"API reponse: \n\t{_response}")
    response: str = _response['choices'][0]['message']['content']
    return response