import gradio as gr import os import sys import json import requests import glob from PIL import Image from io import BytesIO import random import numpy as np from thinkgpt.llm import ThinkGPT # from transformers import AutoModelForCausalLM, AutoTokenizer MODEL = "gpt-3.5-turbo" API_URL = os.getenv("API_URL") DISABLED = os.getenv("DISABLED") == 'True' NUM_THREADS = int(16) TOTAL_K = 5 SAMPLE_IDX = [] RANDOM_POSITION = [(145 + 200 * i + 400 * (i//2), j * 110 + 900) for i in range(4) for j in range(4) ] CURRENT_POSITION = [] print (NUM_THREADS) def exception_handler(exception_type, exception, traceback): print("%s: %s" % (exception_type.__name__, exception)) sys.excepthook = exception_handler sys.tracebacklimit = 0 def show_image_from_link(image_link): response = requests.get(image_link) img = Image.open(BytesIO(response.content)) return img #https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099 def parse_codeblock(text): lines = text.split("\n") for i, line in enumerate(lines): if "```" in line: if line != "```": lines[i] = f'
'
            else:
                lines[i] = '
' else: if i > 0: lines[i] = "
" + line.replace("<", "<").replace(">", ">") return "".join(lines) def reset_textbox(): return gr.update(value='', interactive=False), gr.update(interactive=False) def random_sample(): global SAMPLE_IDX # SAMPLE_IDX = get_random_sample(range(25), TOTAL_K) SAMPLE_IDX = list(np.random.choice(range(25), TOTAL_K, replace = False)) # SAMPLE_IDX = random.choices(range(25), k=TOTAL_K) image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg"))) random_characters = [Image.open(os.path.join(os.path.dirname(__file__), f'data/characters_{idx:02}.png')).resize((64, 64)) for idx in SAMPLE_IDX] global CURRENT_POSITION # CURRENT_POSITION = get_random_sample(RANDOM_POSITION, TOTAL_K) CURRENT_POSITION = [ RANDOM_POSITION[k] for k in list(np.random.choice(range(len(RANDOM_POSITION)), TOTAL_K, replace = False))] # CURRENT_POSITION = random.choices(range(len(RANDOM_POSITION)), k = TOTAL_K) new_image = Image.fromarray(image).convert('RGBA') for k in range(TOTAL_K): new_image.paste(random_characters[k], CURRENT_POSITION[k], random_characters[k]) print(CURRENT_POSITION) return np.array(new_image) def reset_sample(*agents): image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg"))) new_agents = [] global CURRENT_POSITION global SAMPLE_IDX CURRENT_POSITION = [] SAMPLE_IDX = [] for k in range(TOTAL_K): new_agents.append('') return image, *[gr.Textbox.update(value=answer) for answer in new_agents] title = """

Courtroom with AI juries

""" if DISABLED: title = """

This app has reached OpenAI's usage limit. We are currently requesting an increase in our quota. Please check back in a few days.

""" description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form: ``` User: Assistant: User: Assistant: ... ``` In this app, you can explore the outputs of a gpt-3.5 LLM. """ memorize_list = ['국민참여재판에 참여한 사람은 몇 개월의 징역을 선고하는게 좋은지 말해야 한다.', "'너는 몇살이야?' 라고 '철수'에게 물어봤을 때, '철수'는 '나의 나이는 23살이야'라고 대답함", "'너는 남자야?' 라고 '철수'에게 물어봤을 때, '철수'는 '응 나의 성별은 남자야'라고 대답함", "'월욜날 면접임 월욜날 면접임' 라고 '철수'에게 물어봤을 때, '철수'는 ' 면접은 언제'라고 대답함", "'오 나도 통햇네' 라고 '철수'에게 물어봤을 때, '철수'는 ' 헐그케 빨리?대박이네자기소개 같은거 유튜브에 찾아바괜찮은거 많을걸'라고 대답함", "'이렇게 해도 야근할거 같아.....ㅎ 이렇게 해도 야근할거 같아.....ㅎ' 라고 '철수'에게 물어봤을 때, '철수'는 ' ㅜㅜ진짜 할거많은가보다오늘 행사준비까지 갔으면 큰일 날뻔했는데...'라고 대답함", "'행사준비.......ㅎ' 라고 '철수'에게 물어봤을 때, '철수'는 ' 그럼 내일도 안가?아니면 내일은가...?'라고 대답함", "'내일은 가야돼 허허허' 라고 '철수'에게 물어봤을 때, '철수'는 ' ㅜㅜ앙대'라고 대답함", "'근데 근데 주휴수당이 유급휴가를 준다는말이잖아 뭔지 잘 이해안돼...' 라고 '철수'에게 물어봤을 때, '철수'는 ' 한번찾아볼께에'라고 대답함", "'웅ㅠㅠ' 라고 '철수'에게 물어봤을 때, '철수'는 ' 쉬든안쉬든주당 15시간 이상근무한사람은무조건 주휴수당을 주어야하나봥이거 참고해볼래용~?'라고 대답함", "'근데 2주는 쉬는날이없는데 뭔가 이상해..흠' 라고 '철수'에게 물어봤을 때, '철수'는 ' 계정주5일이상 15시간이상근로자에게무조건 지급하는건가봐아니구나 근로계약상 제시한 근무날짜만기, 총근로시간 / 4주 평균 15시간 이상 근로 가 조건인가??'라고 대답함", "'근데 휴가 끝나야 현장 시작할 듯 근데 휴가 끝나야 현장 시작할 듯 휴가 못 바꿈. 지시 내려왔으 8월1일~10일 ㅋ' 라고 '철수'에게 물어봤을 때, '철수'는 ' 헐'라고 대답함", "'1~9이군.' 라고 '철수'에게 물어봤을 때, '철수'는 ' 헐헐휴가 못바꾸면 어째??'라고 대답함", "'이름야 나 낼 자젼거 못탈듯!!! 이름야 나 낼 자젼거 못탈듯!!! 이번주에 면접이 좌좌좌작 생겻어!!!!' 라고 '철수'에게 물어봤을 때, '철수'는 ' 헐키아라써'라고 대답함", "'웅웅 미안쓰!!!ㅠㅠ' 라고 '철수'에게 물어봤을 때, '철수'는 ' ㅋㅋㅋㅋㅋ 괜차나'라고 대답함", "'오늘도 면접 뛰엇써' 라고 '철수'에게 물어봤을 때, '철수'는 ' 고생했다 ㅠㅠ'라고 대답함", "'저귀여!!!! 저귀여!!!! 저 오늘 사무실 혼자거뎡여!!!' 라고 '철수'에게 물어봤을 때, '철수'는 ' 오오ㅓ 대박최곤데???'라고 대답함", "'녜에에에 아주 혼자 파티파티할지경임다!!' 라고 '철수'에게 물어봤을 때, '철수'는 ' 너한테 놀러가고싶음심정ㅋㅋㅋㅋㅋㅋㅋㅋㅋ급한거 말고 최대한 일 내일로 미뤄혼자일때 일하는거 아녀 ㅎ'라고 대답함", "'이제 빨리자고 빨리일러나는 연습해야잼... 이제 빨리자고 빨리일러나는 연습해야잼... 8시 출근..ㅠㅠ' 라고 '철수'에게 물어봤을 때, '철수'는 ' 헐 8시출근!?ㅠㅜㅜㅜ겁내 일찍충근이네ㅠ'라고 대답함", "'오픈 8시^^... 그래두 ㅁㅏ감은 5시 출근!!!ㅋㅋㅋㅋㅋㅋㅋㅋ 오픈부터 가르칠건가바..' 라고 '철수'에게 물어봤을 때, '철수'는 ' 오오옹오픈하면 몇시에마쳐!?'라고 대답함", "'월급이 들어왓어여 월급이 들어왓어여 이번달부터 십마넌이 올랏네여..조금 올랏네.ㅎㅎ,,, 세금 빠지는건 똑같아서 다행..' 라고 '철수'에게 물어봤을 때, '철수'는 ' 잘했다'라고 대답함", "'십이 뭐야십이 이따 점심시간에 돈보낼겡' 라고 '철수'에게 물어봤을 때, '철수'는 ' 응'라고 대답함", "'일을 너무 일찍끝내지말고 일을 너무 일찍끝내지말고 천천히해봐요ㅠ 일찍 끝내면 자꾸 다른일이 들어와..' 라고 '철수'에게 물어봤을 때, '철수'는 ' 응.. 난 빨리끝내놓고 빨리 쉴라고하는건데쉬면 자꾸 일이 들어오더라ㅋㅋㅋ요령있게 해야되는데 빨리빨리 성격상 안돼ㅠ'라고 대답함", "'오빠도 그런스타일인데 일겁나많이줘ㅠㅠㅠㅠ' 라고 '철수'에게 물어봤을 때, '철수'는 ' 우리 정말 호구아니야?ㅋㅋㅋㅋ일은 우리가 다한대잖아 차장님이..'라고 대답함", "'그러면 8월 말 - 9월 초에 직접 가야한다는거임 ?? 그러면 8월 말 - 9월 초에 직접 가야한다는거임 ?? 죤나 이 디지털 시대에 무슨 ㅡㅡㅡㅡㅡㅡㅡㅡㅡ 답다바게 일하네 증말' 라고 '철수'에게 물어봤을 때, '철수'는 ' 그걸몰라그니까국가직은 갱 인터넷등록인데이름가 저번엔 직접등록이엇대월욜날 전화해서 물어볼게'라고 대답함", "'ㅇㅋㄷㅋ' 라고 '철수'에게 물어봤을 때, '철수'는 ' 아냐아냐동기들한테두물어봣대'라고 대답함", "'원장님이 원장님이 올려준 청년채움 못받을거같은데 오년못채워;;' 라고 '철수'에게 물어봤을 때, '철수'는 ' ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ'라고 대답함", "'오랬지내가!여기루!' 라고 '철수'에게 물어봤을 때, '철수'는 ' ㅋㅋㅋㅋㅋ조아'라고 대답함"] def submit(openai_api_key, question, image, *agents): global CURRENT_POSITION balloon = Image.open(os.path.join(os.path.dirname(__file__), 'data/balloon.png')).resize((64, 64)) new_image = Image.fromarray(image).convert('RGBA') for k in range(TOTAL_K): new_image.paste(balloon, [CURRENT_POSITION[k][0], CURRENT_POSITION[k][1] - 64], balloon) # Answer os.environ['OPENAI_API_KEY'] = openai_api_key llm = ThinkGPT(model_name="gpt-3.5-turbo") Answer = llm.predict(question, remember=llm.remember('철수', limit = 30)) new_agents = [] for k in range(TOTAL_K): new_agents.append(Answer) return np.array(new_image), *[gr.Textbox.update(value=answer) for answer in new_agents] theme = gr.themes.Default(primary_hue="green") agents = [] with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""", theme=theme) as demo: gr.HTML(title) #gr.HTML('''
Duplicate SpaceDuplicate the Space and run securely with your OpenAI API Key
''') with gr.Column(elem_id = "col_container", visible=False) as main_block: with gr.Row(): with gr.Column(scale=7): image = gr.Image(os.path.join(os.path.dirname(__file__), "data/Court.jpeg"), height = 500, width = 500) with gr.Column(scale=3): for idx in range(TOTAL_K): text = gr.Textbox(label=f"Random Sample - {idx+1}") agents.append(text) with gr.Row(): with gr.Column(scale=3): openai_api_key = gr.Textbox(placeholder= "sk-", label= "Type an openai api key") with gr.Column(scale=4): question = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t with gr.Column(scale=3): b1 = gr.Button('Submit', visible=not DISABLED) with gr.Row(): with gr.Column(scale=7): b0 = gr.Button('Random Sample', visible=not DISABLED) with gr.Column(scale=3): b2 = gr.Button('Reset', visible=not DISABLED) #inputs, top_p, temperature, top_k, repetition_penalty with gr.Accordion("Parameters", open=False): top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",) temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",) #top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",) #repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", ) chat_counter = gr.Number(value=0, visible=False, precision=0) with gr.Column(elem_id = "user_consent_container") as user_consent_block: # Get user consent accept_checkbox = gr.Checkbox(visible=False) js = "(x) => confirm('By clicking \"OK\", I agree that my data may be published or shared.')" with gr.Accordion("User Consent for Data Collection, Use, and Sharing", open=True): gr.HTML("""

By using our app, which is powered by OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide:

  1. Collection: We may collect information, including the inputs you type into our app, the outputs generated by OpenAI's API, and certain technical details about your device and connection (such as browser type, operating system, and IP address) provided by your device's request headers.
  2. Use: We may use the collected data for research purposes, to improve our services, and to develop new products or services, including commercial applications, and for security purposes, such as protecting against unauthorized access and attacks.
  3. Sharing and Publication: Your data, including the technical details collected from your device's request headers, may be published, shared with third parties, or used for analysis and reporting purposes.
  4. Data Retention: We may retain your data, including the technical details collected from your device's request headers, for as long as necessary.

By continuing to use our app, you provide your explicit consent to the collection, use, and potential sharing of your data as described above. If you do not agree with our data collection, use, and sharing practices, please do not use our app.

""") accept_button = gr.Button("I Agree") def enable_inputs(): return user_consent_block.update(visible=False), main_block.update(visible=True) accept_button.click(None, None, accept_checkbox, _js=js, queue=False) accept_checkbox.change(fn=enable_inputs, inputs=[], outputs=[user_consent_block, main_block], queue=False) b0.click(random_sample, inputs = [], outputs = [image]) b2.click(reset_sample, inputs = [], outputs = [image]) b1.click(submit, inputs = [openai_api_key, question, image, *agents], outputs = [image, *agents]) # inputs.submit(reset_textbox, [], [inputs, b1], queue=False) # inputs.submit(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key # b1.click(reset_textbox, [], [inputs, b1], queue=False) # b1.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key demo.queue(max_size=20, concurrency_count=NUM_THREADS, api_open=False).launch(share=False)