RASMUS commited on
Commit
2c61137
·
1 Parent(s): 127b8af
Files changed (1) hide show
  1. app.py +152 -0
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from io import StringIO
4
+ import openai
5
+ import pytesseract
6
+
7
+
8
+
9
+ import os
10
+
11
+ import numpy as np
12
+ import time
13
+
14
+ # Set up OpenAI API key
15
+ from api_key import api_key
16
+ openai.api_key = os.environ["CHATGPT_API_KEY"]
17
+
18
+ Init_system_prompt = "You are an AI Assistant that tries to teach kids various subjects. You are given learning material and you task is to ask questions given the material and then you also grade answers and give feedback how to improve the answers"
19
+ system_message = {"role": "system", "content": Init_system_prompt}
20
+
21
+ import os
22
+ from PIL import Image
23
+
24
+ import pytesseract
25
+ #os.system("rm -f path.txt")
26
+ path = os.system("which tesseract >> path.txt")
27
+ with open("path.txt", 'r') as file:
28
+ tesseract_path = file.read().replace('\n', '')
29
+
30
+
31
+ ########### TAB 1 (UPLOAD) FUNCTIONS #############################
32
+
33
+ def print_files(files):
34
+ for file in files:
35
+ print(file.__dir__())
36
+ print(file.name)
37
+ print(file.file)
38
+
39
+
40
+ def create_data(files):
41
+ question_context = ''
42
+ for file in files:
43
+ if file.name.endswith('png') or file.name.endswith('.jpg'):
44
+ try:
45
+ question_context += (pytesseract.image_to_string(Image.open(file.name), lang='fin')) + '\n\n'
46
+ except Exception as e:
47
+ print(e)
48
+ pass
49
+
50
+ return question_context
51
+
52
+
53
+ ########### TAB 2 (CHROMA + PLOT) FUNCTIONS #############################
54
+
55
+ ########### TAB 3 (CHAT) FUNCTIONS #############################
56
+
57
+ def user(user_message, history):
58
+ return "", history + [[user_message, None]]
59
+
60
+ def bot(history, messages_history, system_prompt, teksti_contexti, temperature, max_tokens, chatgpt_model):
61
+ user_message = history[-1][0]
62
+
63
+ bot_message, messages_history = ask_gpt(user_message, messages_history, system_prompt, teksti_contexti, temperature, max_tokens,chatgpt_model)
64
+ messages_history += [{"role": "assistant", "content": bot_message}]
65
+ history[-1][1] = bot_message
66
+ time.sleep(0.2)
67
+ return history, messages_history, str(messages_history)
68
+
69
+ def ask_gpt(message, messages_history, context, system_prompt, temperature, max_tokens, chatgpt_model):
70
+ if len(messages_history) < 1:
71
+ messages_history = [{"role": "system", "content": system_prompt}]
72
+ messages_history += [{"role": "user", "content": context + '\n Please ask a question about the previous paragramph?'}]
73
+ print(messages_history)
74
+ response = openai.ChatCompletion.create(
75
+ model=chatgpt_model,
76
+ messages=messages_history,
77
+ temperature=temperature,
78
+ max_tokens=max_tokens
79
+ )
80
+ return response['choices'][0]['message']['content'], messages_history
81
+
82
+ def init_history(messages_history, system_prompt):
83
+ messages_history = []
84
+ messages_history += [{"role": "system", "content": system_prompt}]
85
+ msg_log = gr.Textbox.update(value="Tähän tulee message history")
86
+ system_prompt = gr.Textbox.update(value=system_prompt, label='Insert system message here')
87
+ return messages_history, system_prompt, msg_log
88
+
89
+
90
+ ############# INTERFACE ##########################
91
+ with gr.Blocks() as demo:
92
+ gr.Markdown("ChatGPT demo with RAG using Chromadb")
93
+
94
+
95
+
96
+ ############# TAB 1 ##########################
97
+ with gr.Tab("Upload documents"):
98
+ with gr.Row():
99
+ files = gr.File(file_count='multiple', file_types=['image'], interactivate = True)
100
+ gr.Markdown("")
101
+ testi = gr.Button()
102
+
103
+ ############# TAB 2 ##########################
104
+ with gr.Tab("Create questions"):
105
+
106
+ with gr.Row():
107
+ gr.Markdown("")
108
+ with gr.Row():
109
+ create_context_btn = gr.Button()
110
+ teksti_contexti = gr.Textbox(value='Tähän tulee konteksti', label='Dataframe columns')
111
+
112
+ ############# TAB 3 ##########################
113
+
114
+ with gr.Tab("Chat"):
115
+ gr.Markdown("""<h1><center>ChatGPT
116
+ ChatBot with Gradio and OpenAI</center></h1>
117
+ """)
118
+ with gr.Row():
119
+ system_prompt = gr.Textbox(value=Init_system_prompt, label='Insert system message here')
120
+ chatgpt_model = gr.Dropdown(choices=["gpt-3.5-turbo", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613"], value='gpt-3.5-turbo',label='ChatGPT model to use', interactive=True)
121
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, value=0.0, label='temperature')
122
+ max_tokens = gr.Slider(minimum=10, maximum=600, step=10, value=100, label='Max tokens')
123
+ with gr.Row():
124
+ chatbot = gr.Chatbot(label='ChatGPT Chat')
125
+ state = gr.State([])
126
+ with gr.Row():
127
+ msg = gr.Textbox()
128
+ with gr.Row():
129
+ clear = gr.Button("Clear")
130
+ with gr.Row():
131
+ msg_log = gr.Textbox("Tähän tulee message history", label='Message history')
132
+
133
+
134
+ with gr.Accordion("Klikkaa avataksesi ohjeet"):
135
+ gr.Markdown("Ohjeet tulee tänne")
136
+
137
+
138
+ # TAB 1 (UPLOAD) Interactive elements:
139
+ testi.click(print_files, [files])
140
+
141
+ # TAB 2 (CHROMA + PLOT) Interactive elements:
142
+ create_context_btn.click(create_data, files, teksti_contexti)
143
+
144
+
145
+ # TAB 3 (CHAT) Interactive elements:
146
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
147
+ bot, [chatbot, state, system_prompt, teksti_contexti, temperature, max_tokens, chatgpt_model], [chatbot, state, msg_log]
148
+ )
149
+ clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state, system_prompt], [state, system_prompt, msg_log])
150
+
151
+
152
+ demo.launch(debug=True)