2023. 11. 23. 00:52

# babel_fish.py
import tkinter as tk
from tkinter import ttk
import openai
import sounddevice as sd
from gtts import gTTS
import pygame
import wavio
from openai import OpenAI
import os

API_KEY = os.environ.get('OPEN_API_KEY')
client = OpenAI(
api_key = API_KEY,
)

# create a dictionary to store the language and
# their corresponding codes
languages = {'English': 'en', 'Spanish': 'es', 'French': 'fr', 'Korean': 'ko', 'Japanese': 'ja'}

app = tk.Tk()
app.title("Babel Fish")
style = ttk.Style()

def set_wait_cursor():
    submit_btn.config(cursor="watch")
    app.update_idletasks()  # Force an immediate update of the window


def set_normal_cursor():
    submit_btn.config(cursor="")

def translate(language1, language2, text):
    set_label("Translating...")
    prompt = f"Translate the following from {language1} to {language2}: {text}"
    # prompt = 'Hi There'
    messages = [{'role': 'user', 'content': prompt}]
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=0.8,
        top_p=1.0,
        frequency_penalty=0.0,
        presence_penalty=0.6,
    )

    chat_gpt_translation = response.choices[0].message.content
    print('translation: ' + chat_gpt_translation)
    return chat_gpt_translation


def text_to_speech(translated_text, language):
    set_label("Playing...")
    tts = gTTS(translated_text, lang=languages[language], slow=False)
    tts.save('C:\\temp\\translation.mp3')
    # 5. Convert Translated Text to Speech
    # Placeholder for a TTS service (like Google Cloud TTS).

    # Initialize pygame mixer
    pygame.mixer.init()
    pygame.mixer.music.load('C:\\temp\\translation.mp3')
    pygame.mixer.music.play()


# If you want to keep the program running until the audio is done playing:
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)  # This will wait and let the music play.

    # close the mp3 file
    pygame.mixer.music.stop()
    pygame.mixer.quit()
    os.remove('C:\\temp\\translation.mp3')


def capture_audio():
     # Indicate start of recording
    label_recording.config(text="Recording...", bg="red")

    app.update()
    # get number of seconds from dropdown
    duration = int(combo_duration.get())
    samplerate = 44100
    audio = sd.rec(int(samplerate * duration),
                   samplerate=samplerate, channels=2, dtype='int16')
    sd.wait()

    label_recording.config(text="Finished Recording", bg="green")

    app.update()

    # Save the numpy array to a WAV file using wavio
    wav_path = "c:\\temp\\myrecording.wav"
    wavio.write(wav_path, audio, samplerate, sampwidth=2)


def set_label(text):
    label_recording.config(text=text, bg="green", fg="white")
    label_recording.update()


def transcribe():
    audio_file = open("c:\\temp\\myrecording.wav", "rb")
    set_label("Transcribing...")
    transcription = client.audio.transcriptions.create(
     model='whisper-1', file=audio_file, response_format='text')
    audio_file.close()
    print('transcription: ' + f'{transcription}\n\n')
    return transcription

def reset_status():
    label_recording.config(text="Click the button to start recording",
                           bg="lightgray", fg="white")
    label_recording.update()


def submit():

set_wait_cursor()

# 1. Capture Audio
capture_audio()

# 2. Transcibe the Audio
transcription = transcribe()

# 3. Translate the Transcribed Audio
resulting_traslation = translate(combo1.get(), combo2.get(), transcription)

# 4, Voice the Translated Text
text_to_speech(resulting_traslation, combo2.get())
reset_status()
set_normal_cursor()

# Label and ComboBox for the Known Language
label1 = ttk.Label(app, text="Select Known Language")
label1.grid(column=0, row=0, padx=10, pady=5)
combo1 = ttk.Combobox(app, values=list(languages.keys()))
combo1.grid(column=1, row=0, padx=10, pady=5)
combo1.set("English")

# Label and ComboBox for the Translated Language
label2 = ttk.Label(app, text="Select Traslated Language")
label2.grid(column=0, row=1, padx=10, pady=5)
combo2 = ttk.Combobox(app, values=list(languages.keys()))
combo2.grid(column=1, row=1, padx=10, pady=5)
combo2.set("Spanish")

label_recording_duration = tk.Label(app, text="Recoding Duration(seconds):")
label_recording_duration.grid(column=0, row=2, padx=10, pady=5)
combo_duration = ttk.Combobox(app, values=[5, 10, 15, 20, 25, 30])
combo_duration.grid(column=1, row=2, padx=10, pady=5)
combo_duration.set(5)

# Button to submit the text to traslate
submit_btn = ttk.Button(app, text="Record", command=submit)
submit_btn.grid(column=1, row=3, padx=10, pady=20)
label_recording = tk.Label(app, text="Click the button to start recording",
bg="lightgray", fg="white", width=60, height=2)
label_recording.grid(column=0, columnspan=2, row=4, padx=10, pady=20)

app.mainloop()



'python' 카테고리의 다른 글

pdf 출력  (0) 2023.11.22
사자와 코끼리가 휴대폰 대리점에 나누는 대화  (2) 2023.11.22
챗gpt 전체소스  (1) 2023.11.22
dall-e-3 image 생성 - 한국어로 변경  (1) 2023.11.22
dall-e-3를 활용한 이미지 생성  (0) 2023.11.22
Posted by 다만사
2023. 11. 22. 19:28
import tkinter as tk
from io import BytesIO
from tkinter import ttk, messagebox
import openai
import os
import requests
from PIL import Image, ImageTk
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Image as ReportLabImage, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont

API_KEY = os.environ.get('OPENAI_API_KEY')
openai.api_key = API_KEY

pil_image_path = "c:\\temp\\animal_play_image.png"

def create_pdf(dialog_text):
if len(dialog_text) == 0:
messagebox.showerror("Error",
"Please generate the dialog first!")
return
pdfmetrics.registerFont(TTFont("맑은고딕", "malgun.ttf"))
doc = SimpleDocTemplate("output.pdf", papersize=letter)

contents = []
img = ReportLabImage(pil_image_path,
width=2.5*inch,
height=2.5*inch)
contents.append(img)

dialog_text = '<br/>' + dialog_text
dialog_text = dialog_text.replace('\n', '<br/><br/>')
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(
name="Hangul",
fontName="맑은고딕"
))
paragraph = Paragraph(dialog_text, styles['Hangul'])

contents.append(paragraph)

doc.build(contents)

messagebox.showinfo("PDF Created", "PDF created successfully!")


def generateImage(animal1, animal2, scenario):
response = openai.Image.create(
model='dall-e-3',
#prompt=f"cartoon image of a {animal1} and a {animal2} discussing {scenario}",
prompt=f"{animal1}() {animal2}() {scenario}에서 이야기하고 있는 카툰 이미지",
n=1,
size="1024x1024",
response_format="url"
)

image_url = response.data[0]["url"]
return image_url

def update_label_with_new_image(label, photo):
label.config(image=photo)
label.image = photo

def display_image_from_url(image_holder, url):
response = requests.get(url)
image_data = BytesIO(response.content)

image = Image.open(image_data)
image.save(pil_image_path, "PNG")
photo = ImageTk.PhotoImage(image)

update_label_with_new_image(image_holder, photo)


def submit():
animal1 = combo1.get()
animal2 = combo2.get()
scenario = entry_box.get()
# 사자와 판다사이에 각각의 동물이 서로 말을 주고받는 10줄의 연극대본을 작성하여라. 작성할 시나리오는 다음과 같다. 그들이 만나는 장소: 스타벅스
# prompt = f"Create a play between a {animal1} and a {animal2} with 10 lines of dialog with each animal taking " \
# f"turns to speak. Hear the scenario in which they will engage: {scenario}\n";
prompt = f"{animal1}() {animal2}사이에 각각의 동물이 서로 말을 주고받는 10줄의 연극대본을 작성하여라. 작성할 시나리오는 다음과 같다. 그들이 만나는 장소: {scenario}\n"


messages = [{'role': 'user', 'content': prompt}]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages = messages,
temperature=0.8,
presence_penalty=0.6,
)

chatGPTAnswer = response["choices"][0]["message"]["content"]
print(chatGPTAnswer)

result_text.config(state="normal")
result_text.delete(1.0, tk.END) # Clear any previous results
# result_text.insert(tk.END, f"Animal 1: {animal1}\n")
# result_text.insert(tk.END, f"Animal 2: {animal2}\n")
# result_text.insert(tk.END, f"Discussion scenario: {scenario}\n")
result_text.insert(tk.END, chatGPTAnswer)
result_text.config(state="disabled")

image_url = generateImage(animal1, animal2, scenario)
display_image_from_url(image_holder, image_url)

app = tk.Tk()
app.title("Animal Discussion Scenario")

# Label and ComboBox for the first animal
label1 = ttk.Label(app, text="Select Animal 1:")
label1.grid(column=0, row=0, padx=10, pady=5)
combo1 = ttk.Combobox(app, values=["사자", "코끼리", "기린", "캥거루", "판다"])
combo1.grid(column=1, row=0, padx=10, pady=5)
combo1.set("사자")

#Label and ComboBox for the second animal
label2 = ttk.Label(app, text="Select Animal 2:")
label2.grid(column=0, row=1, padx=10, pady=5)
combo2 = ttk.Combobox(app, values=["사자", "코끼리", "기린", "캥거루", "판다"])
combo2.grid(column=1, row=1, padx=10, pady=5)
combo2.set("코끼리")

# Label and Entry for entering the discussion scenario
label3 = ttk.Label(app, text="Enter Discussion Scenario:")
label3.grid(column=0, row=2, padx=10, pady=5)
entry_box = ttk.Entry(app, width=30)
entry_box.grid(column=1, row=2, padx=10, pady=5)

# Button to submit the details
submit_btn = ttk.Button(app, text="Submit", command=submit)
submit_btn.grid(column=1, row=3, padx=10, pady=20)

# Button to submit the details to pdf
create_pdf_btn = ttk.Button(app, text="Create Pdf", command=
lambda: create_pdf(result_text.get(1.0, tk.END)))
create_pdf_btn.grid(column=2, row=3, padx=10, pady=20)

# scrollbar
scrollbar = tk.Scrollbar(app)
scrollbar.grid(row=4, column=3, sticky='ns')

# Text widget to display results
result_text = tk.Text(app, width=40, height=10, wrap=tk.WORD, yscrollcommand=scrollbar.set)
result_text.grid(column=0, row=4, columnspan=2, padx=10, pady=10)

scrollbar.config(command=result_text.yview)

image_holder = tk.Label(app)
image_holder.grid(column=0, row=5, columnspan=4, padx=10, pady=10)

app.mainloop()

'python' 카테고리의 다른 글

babel fish  (1) 2023.11.23
사자와 코끼리가 휴대폰 대리점에 나누는 대화  (2) 2023.11.22
챗gpt 전체소스  (1) 2023.11.22
dall-e-3 image 생성 - 한국어로 변경  (1) 2023.11.22
dall-e-3를 활용한 이미지 생성  (0) 2023.11.22
Posted by 다만사
2023. 11. 22. 18:08

장면: 휴대폰 대리점

(사자가 대리점에 도착한다. 코끼리는 이미 대기 중이다.)

사자: 안녕, 코끼리! 너도 휴대폰을 고치러 왔니?

코끼리: 네, 맞아. 내 휴대폰이 이상해져서 왔어. 너도 그래?

사자: 그래, 내 휴대폰 카메라가 작동하지 않아서 왔어. 고쳐줄 수 있을까?

코끼리: 그럼 우리 둘 다 기다려야겠네.

(사자와 코끼리가 대기하고 있는데 개구리가 들어온다.)

개구리: 어이, 여기가 휴대폰 대리점이구나! 나도 휴대폰 고치려고 왔어.

사자: 안녕, 개구리! 휴대폰에 문제가 생겼니?

개구리: 그래, 배터리가 너무 빨리 닳아서 왔어. 너희들은 무슨 문제야?

코끼리: 나는 휴대폰이 자꾸 꺼져버려서 왔어.

(갑자기 원숭이가 대리점에 들어온다.)

원숭이: 이런, 여긴 휴대폰 대리점이구나! 내 휴대폰도 고치러 왔어.

사자: 안녕, 원숭이! 무슨 문제가 생겼어?

원숭이: 내 휴대폰 터치스크린이 제대로 작동하지 않아서 왔어. 너희들은 어떤 문제야?

개구리: 나는 배터리 문제야.

코끼리: 나는 전원 문제야.

(여우가 대리점에 들어온다.)

여우: 저기, 여긴 휴대폰 대리점이지? 나도 휴대폰을 수리해야 해서 왔어.

사자: 맞아, 여우! 우리도 여기 왔어. 무슨 문제가 생겼어?

여우: 내 휴대폰 스피커에서 이상한 소리가 나와서 왔어. 다른 사람들은 어떤 문제인지 아니?

원숭이: 나는 터치스크린 문제야.

개구리: 나는 배터리 문제야.

코끼리: 나는 전원 문제야.

(사자가 대리점 직원에게 다가가서 상담을 한다.)

사자: 죄송해요, 우리 다섯 명 모두 휴대폰 문제로 왔어요. 도와주실 수 있을까요?

대리점 직원: 물론이죠. 각각의 문제를 검토해 보고 최대한 빨리 해결해드릴게요.

(연극은 계속되며, 사자, 코끼리, 개구리, 원숭이, 여우는 대리점 직원과 함께 휴대폰을 수리하는 과정을 보여준다.)

 

'python' 카테고리의 다른 글

babel fish  (1) 2023.11.23
pdf 출력  (0) 2023.11.22
챗gpt 전체소스  (1) 2023.11.22
dall-e-3 image 생성 - 한국어로 변경  (1) 2023.11.22
dall-e-3를 활용한 이미지 생성  (0) 2023.11.22
Posted by 다만사
2023. 11. 22. 14:30
import tkinter as tk
from io import BytesIO
from tkinter import ttk
import openai
import os
import requests
from PIL import Image, ImageTk

API_KEY = os.environ.get('OPENAI_API_KEY')
openai.api_key = API_KEY

def generateImage(animal1, animal2, scenario):
response = openai.Image.create(
model='dall-e-3',
#prompt=f"cartoon image of a {animal1} and a {animal2} discussing {scenario}",
prompt=f"{animal1}() {animal2}() {scenario}에서 이야기하고 있는 카툰 이미지",
n=1,
size="1024x1024",
response_format="url"
)

image_url = response.data[0]["url"]
return image_url

def update_label_with_new_image(label, photo):
label.config(image=photo)
label.image = photo

def display_image_from_url(image_holder, url):
response = requests.get(url)
image_data = BytesIO(response.content)

image = Image.open(image_data)
photo = ImageTk.PhotoImage(image)

update_label_with_new_image(image_holder, photo)


def submit():
animal1 = combo1.get()
animal2 = combo2.get()
scenario = entry_box.get()
# 사자와 판다사이에 각각의 동물이 서로 말을 주고받는 10줄의 연극대본을 작성하여라. 작성할 시나리오는 다음과 같다. 그들이 만나는 장소: 스타벅스
# prompt = f"Create a play between a {animal1} and a {animal2} with 10 lines of dialog with each animal taking " \
# f"turns to speak. Hear the scenario in which they will engage: {scenario}\n";
prompt = f"{animal1}() {animal2}사이에 각각의 동물이 서로 말을 주고받는 10줄의 연극대본을 작성하여라. 작성할 시나리오는 다음과 같다. 그들이 만나는 장소: {scenario}\n"


messages = [{'role': 'user', 'content': prompt}]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages = messages,
temperature=0.8,
presence_penalty=0.6,
)

chatGPTAnswer = response["choices"][0]["message"]["content"]
print(chatGPTAnswer)

result_text.config(state="normal")
result_text.delete(1.0, tk.END) # Clear any previous results
# result_text.insert(tk.END, f"Animal 1: {animal1}\n")
# result_text.insert(tk.END, f"Animal 2: {animal2}\n")
# result_text.insert(tk.END, f"Discussion scenario: {scenario}\n")
result_text.insert(tk.END, chatGPTAnswer)
result_text.config(state="disabled")

image_url = generateImage(animal1, animal2, scenario)
display_image_from_url(image_holder, image_url)

app = tk.Tk()
app.title("Animal Discussion Scenario")

# Label and ComboBox for the first animal
label1 = ttk.Label(app, text="Select Animal 1:")
label1.grid(column=0, row=0, padx=10, pady=5)
combo1 = ttk.Combobox(app, values=["사자", "코끼리", "기린", "캥거루", "판다"])
combo1.grid(column=1, row=0, padx=10, pady=5)
combo1.set("사자")

#Label and ComboBox for the second animal
label2 = ttk.Label(app, text="Select Animal 2:")
label2.grid(column=0, row=1, padx=10, pady=5)
combo2 = ttk.Combobox(app, values=["사자", "코끼리", "기린", "캥거루", "판다"])
combo2.grid(column=1, row=1, padx=10, pady=5)
combo2.set("코끼리")

# Label and Entry for entering the discussion scenario
label3 = ttk.Label(app, text="Enter Discussion Scenario:")
label3.grid(column=0, row=2, padx=10, pady=5)
entry_box = ttk.Entry(app, width=30)
entry_box.grid(column=1, row=2, padx=10, pady=5)

# Button to submit the details
submit_btn = ttk.Button(app, text="Submit", command=submit)
submit_btn.grid(column=1, row=3, padx=10, pady=20)

# scrollbar
scrollbar = tk.Scrollbar(app)
scrollbar.grid(row=4, column=3, sticky='ns')

# Text widget to display results
result_text = tk.Text(app, width=40, height=10, wrap=tk.WORD, yscrollcommand=scrollbar.set)
result_text.grid(column=0, row=4, columnspan=2, padx=10, pady=10)

scrollbar.config(command=result_text.yview)

image_holder = tk.Label(app)
image_holder.grid(column=0, row=5, columnspan=4, padx=10, pady=10)

app.mainloop()
Posted by 다만사
2023. 11. 22. 13:23
import openai
import os

API_KEY = os.environ.get('OPENAI_API_KEY')
openai.api_key = API_KEY
model_engine = "dall-e-3"




def generateImage(animal1, animal2, scenario):
response = openai.Image.create(
model=model_engine,
#prompt=f"cartoon image of a {animal1} and a {animal2} discussing {scenario}",
prompt=f"{animal1}() {animal2}() {scenario}에서 이야기하고 있는 카툰 이미지",
n=1,
size="1024x1024",
response_format="url"
)

image_url = response.data[0]["url"]
return image_url


url = generateImage('호랑이', '러시안 블루 고양이', '스타벅스')
print(url)
 
Posted by 다만사
2023. 11. 22. 13:17

변경api 소스는

Image generation - OpenAI API

import openai
import os

API_KEY = os.environ.get('OPENAI_API_KEY')
openai.api_key = API_KEY
model_engine = "dall-e-3"




def generateImage(animal1, animal2, scenario):
response = openai.Image.create(
model=model_engine,
prompt=f"cartoon image of a {animal1} and a {animal2} discussing {scenario}",
n=1,
size="1024x1024",
response_format="url"
)

image_url = response.data[0]["url"]
return image_url


url = generateImage('Lion', 'Elephant', 'Baseball park')
print(url)

 

Posted by 다만사
2023. 11. 20. 00:29

파이참을 쓸수없는 극한의 상황이라면,(현재상황)
아나콘다에 쥬피터에 서브라임 에디터를 추천한다.
서브라임 에디터 자체는무료는 아니지만, 기능제약없이 무료(?)로 사용가능하다.
 
참고로 윈도우 스토어에서 파이썬은 설치해 두었다.
아나콘다는 2022년 5월버전을 설치하였다.
 

https://repo.anaconda.com/archive/

그리고 D드라이브에 설치위치를 지정한 후
사용하면 된다.
 
 
 

Posted by 다만사
2023. 11. 20. 00:17

from openai import OpenAI
import os

API_KEY = os.environ.get('OPEN_API_KEY')
# openai.api_key = API_KEY

model_engine = "gpt-3.5-turbo"  # gpt-4로도 사용가능...
prompt = "오라클에 대해 설명해줘"

client = OpenAI(
api_key = API_KEY,
)
messages = [{'role':'user', 'content': prompt}]

response = client.chat.completions.create(
model=model_engine,
messages=messages,
temperature=0.8,
presence_penalty=0.6)

chatGPTAnswer = response.choices[0].message.content
print(chatGPTAnswer)

Posted by 다만사
2023. 11. 16. 15:43

<분식집>

(기린과 판다가 분식집에 들어온다. 서로 눈치를 주고받으며 자리에 앉는다.)

기린: (주인공) 안녕, 판다야. 오랜만이네.

판다: (주인공) 그래, 오랜만이야. 어디 갔다온 거야?

기린: (웃음) 사파리에서 좀 놀다왔어. 너도 어디 갔다온 거야?

판다: (웃음) 나는 중국에서 새로운 대나무 숲을 찾아다녀왔어.

기린: 참 대단하군. 대나무 숲이 궁금하다.

판다: 다음에 함께 가보자. 어때?

기린: 좋아, 그럴까? 그럼 우리가 좋아하는 분식을 시키자.

판다: 응, 맞아. 먹고 싶은 분식이 뭐야?

기린: 난 떡볶이와 순대가 좋아. 넌?

판다: 나는 김밥이 좋아. 두 개 시킬까?

기린: 좋아, 그럴까? 그리고 판다야, 앞으로도 자주 만나자.

판다: 그래, 네가 떠나서 그리웠으니까. 앞으로는 더 자주 만나자.

(기린과 판다가 서로 웃으며 음식을 기다린다.)

END

'python' 카테고리의 다른 글

Python 챗GPT 개발환경(4세대 12기가 윈10)  (0) 2023.11.20
ChatGPT 연결코드 수정  (0) 2023.11.20
The Grand Slam Showdown  (0) 2023.11.16
ChatGPT Sample #3 한글  (0) 2023.11.16
ChatGPT Sample #2  (0) 2023.11.16
Posted by 다만사
2023. 11. 16. 15:28

Select Animal 1: Giraffe

Select Animal 2: Kangaroo

Enter Discussion Scenario: baseball park

 

Title: "The Grand Slam Showdown"

Scene: A baseball park. The sun is shining, and the stands are filled with excited spectators.

GIRAFFE: (looking around in awe) Wow, what a magnificent place! So many people and so much green grass! I've never seen anything like this before!

KANGAROO: (hopping closer) G'day, mate! Welcome to the baseball park. It's quite a sight, isn't it? I love the energy here.

GIRAFFE: (leaning down to Kangaroo's level) Absolutely! But I can't help but wonder, how do you even play baseball with those short legs of yours?

KANGAROO: (chuckles) Well, mate, it's all about agility and speed. We kangaroos have powerful hind legs that let us leap and cover ground quickly.

GIRAFFE: (laughs) I suppose my long neck would be quite the advantage when it comes to catching fly balls, though!

KANGAROO: (nodding) That's true, mate! And your height would make you a formidable batter. Just imagine the power of your swing!

GIRAFFE: (smiling) You're right, Kangaroo! We'd make a terrific team. How about we form our own baseball duo and show everyone what we're made of?

KANGAROO: (enthusiastically) I love that idea, Giraffe! Our unique skills combined will surely make us the talk of the park. Let's do it!

GIRAFFE: (extends a hoof) Deal! Together, we'll make this baseball park roar with excitement. Get ready for the Giraffe-Kangaroo Grand Slam Showdown!

KANGAROO: (hops closer and shakes the extended hoof) It's a deal, mate! The crowd won't know what hit 'em. Let's hit a home run and have a blast!

(They both turn towards the baseball field, ready to take on their new adventure together.)

'python' 카테고리의 다른 글

ChatGPT 연결코드 수정  (0) 2023.11.20
ChatGPT(기린과 판다가 분식집에서 만난다면)  (0) 2023.11.16
ChatGPT Sample #3 한글  (0) 2023.11.16
ChatGPT Sample #2  (0) 2023.11.16
Chatgpt Sample  (0) 2023.11.16
Posted by 다만사