dwipper commited on
Commit
22fcf48
·
1 Parent(s): 9d6ebfa

Delete app_old.py

Browse files
Files changed (1) hide show
  1. app_old.py +0 -356
app_old.py DELETED
@@ -1,356 +0,0 @@
1
- import os
2
- import openai
3
- import datetime
4
- import gradio as gr
5
- import json
6
- from jinja2 import Template
7
- import csv
8
- import requests
9
-
10
- # Configuration variables
11
- AIRTABLE_API_KEY = os.getenv("AIRTABLE_API_KEY")
12
-
13
- # Airtable table names
14
- policies_table_name = 'tbla6PC65qZfqdJhE'
15
- prompts_table_name = 'tblYIZEB8m6JkGDEP'
16
- qalog_table_name = 'tbl4oNgFPWM5xH1XO'
17
- examples_table_name = 'tblu7sraOEmRgEGkp'
18
- users_table_name = 'tblLNe5ZL47SvrAEk'
19
- user_log_table_name = 'tblrlTsRrkl6BqMAJ'
20
-
21
- # Define the style and content for the response field
22
- label_text = "NILI Response"
23
- color = "#6562F4"
24
- background_color = "white"
25
- border_radius = "10px"
26
- response_label = f'<h3 style="color: {color}; background-color: {background_color}; border-radius: {border_radius}; padding: 10px;display: inline-block;">{label_text}</h3>'
27
-
28
- # Initialize OpenAI
29
- openai.api_key = os.getenv("OPENAI_API_KEY")
30
-
31
- base_id = 'appcUK3hUWC7GM2Kb'
32
-
33
-
34
- HEADERS = {
35
- "Authorization": f"Bearer {AIRTABLE_API_KEY}",
36
- "Content-Type": "application/json",
37
- "Accept": "application/json",
38
- }
39
-
40
-
41
-
42
- def get_policies(school_selection):
43
-
44
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{policies_table_name}'
45
- school = ''
46
-
47
- # Parameters for the API request to filter by 'school' field and retrieve 'policy_text'
48
- params = {
49
- 'filterByFormula': "OR({})".format(','.join(["school='{}'".format(school) for school in school_selection])),
50
- 'fields[]': 'policy_text', # Replace with the name of your field
51
- }
52
-
53
- #print(params)
54
-
55
- try:
56
- # Send a GET request to the Airtable API
57
- response = requests.get(AIRTABLE_ENDPOINT, headers=HEADERS, params=params)
58
-
59
- # Check if the request was successful (status code 200)
60
- if response.status_code == 200:
61
- # Parse the JSON response
62
- data = response.json()
63
-
64
- # Check if there are records in the response
65
- if data.get('records'):
66
- # Initialize an empty string to store concatenated policies
67
- concatenated_policies = ''
68
-
69
- # Extract the 'policy_text' values from each record and concatenate them
70
- for record in data['records']:
71
- policy_text = record['fields']['policy_text']
72
- if concatenated_policies:
73
- concatenated_policies += "\n----------\n"
74
- concatenated_policies += policy_text
75
-
76
- else:
77
- print("No records found in the 'policies' table for the selected schools.")
78
- else:
79
- print(f"Failed to retrieve data. Status code: {response.status_code}")
80
- except Exception as e:
81
- print(f"An error occurred: {str(e)}")
82
-
83
- #print(concatenated_policies)
84
-
85
- return concatenated_policies
86
-
87
-
88
- def get_schools():
89
-
90
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{policies_table_name}'
91
-
92
- # Parameters for the API request to select only the 'school' field
93
- params = {
94
- 'fields[]': 'school', # Replace with the name of your field
95
- 'sort[0][field]': 'school', # Sort by the 'school' field
96
- 'sort[0][direction]': 'asc', # Sort in ascending order
97
- }
98
-
99
- try:
100
- # Send a GET request to the Airtable API
101
- response = requests.get(AIRTABLE_ENDPOINT, headers=HEADERS, params=params)
102
-
103
- # Check if the request was successful (status code 200)
104
- if response.status_code == 200:
105
- # Parse the JSON response
106
- data = response.json()
107
-
108
- # Check if there are records in the response
109
- if data.get('records'):
110
- # Extract the 'school' values from each record
111
- schools = [record['fields']['school'] for record in data['records']]
112
-
113
- # Print the list of 'school' values
114
- # print(schools)
115
- else:
116
- print("No records found in the 'policies' table.")
117
- else:
118
- print(f"Failed to retrieve data. Status code: {response.status_code}")
119
- except Exception as e:
120
- print(f"An error occurred: {str(e)}")
121
-
122
- return schools
123
-
124
- def get_prompt(header, template_content):
125
-
126
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{prompts_table_name}'
127
-
128
- params = {
129
- 'filterByFormula': "prompt_name='NILI_v1'",
130
- }
131
-
132
- response = requests.get(AIRTABLE_ENDPOINT, headers=HEADERS, params=params)
133
-
134
- # Check for errors
135
- response.raise_for_status()
136
-
137
- data = response.json()
138
-
139
-
140
- # Check if there is at least one record matching the condition
141
- if data.get('records'):
142
- # Get the first record (there should be only one)
143
- record = data['records'][0]['fields']
144
-
145
- # Assign system_prompt and user_prompt to variables
146
- header = record.get('system_prompt', '')
147
- template_content = record.get('user_prompt', '')
148
-
149
- return header, template_content
150
-
151
- def get_examples():
152
-
153
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{examples_table_name}'
154
-
155
- # Send your request and parse the response
156
- response = requests.get(AIRTABLE_ENDPOINT, headers=HEADERS)
157
- data = json.loads(response.text)
158
-
159
- # Check for errors
160
- response.raise_for_status()
161
-
162
- for record in data['records']:
163
- nil_question = record['fields']['nil_question']
164
- ui_examples.append([None, None, None, nil_question])
165
-
166
- #print(ui_examples)
167
-
168
-
169
- def append_to_at_qalog(your_role, school_selection, output_format, input_text, gpt_response,response_time,question_cost,prompt_tokens,completion_tokens):
170
-
171
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{qalog_table_name}'
172
-
173
- # Organize data for Airtable
174
- new_fields = {
175
- 'your_role': str(your_role),
176
- 'school_selection': str(school_selection),
177
- 'output_format': str(output_format),
178
- 'input_text': str(input_text),
179
- 'gpt_response': str(gpt_response),
180
- 'response_time': str(response_time),
181
- 'question_cost': question_cost,
182
- 'user_name': str(logged_in_user),
183
- 'prompt_tokens': prompt_tokens,
184
- 'completion_tokens': completion_tokens
185
- }
186
-
187
- data = {
188
- 'fields': new_fields
189
- }
190
-
191
- try:
192
- # Post data to Airtable
193
- response = requests.post(AIRTABLE_ENDPOINT, headers=HEADERS, json=data)
194
-
195
- # Check for errors
196
- response.raise_for_status()
197
-
198
- except requests.exceptions.HTTPError as http_error:
199
- # Handle the HTTP error (e.g., log it or display an error message)
200
- print(f"HTTP error occurred: {http_error}")
201
-
202
- except Exception as e:
203
- # Handle exceptions, log errors, or raise them as needed
204
- print(f"An error occurred: {str(e)}")
205
-
206
- #Chatbot Function
207
- def chatbot(your_role,school_selection,output_format,input_text):
208
-
209
- start_time = datetime.datetime.now()
210
-
211
- # school_selection holds an array of one or more schools
212
- #print(school_selection)
213
-
214
- # Read the Hydrated policies
215
-
216
- policies = get_policies(school_selection)
217
-
218
- template_content = ''
219
- header = ''
220
-
221
- header, template_content = get_prompt(header, template_content)
222
-
223
- # Create a Jinja2 template from the content
224
- template = Template(template_content)
225
-
226
- # Render the template with the policy JSON
227
- analysis_input = template.render(policies=policies, question=input_text,format=output_format)
228
-
229
- #with open('analysis_input.txt', 'w', encoding='utf-8') as out_file:
230
- #out_file.write(analysis_input)
231
-
232
- response = openai.ChatCompletion.create(
233
- model="gpt-4",
234
- # model="gpt-3.5-turbo",
235
- temperature=0,
236
- messages=[
237
- {
238
- "role": "system",
239
- "content": header
240
- },
241
- {
242
- "role": "user",
243
- "content": analysis_input
244
- }
245
- ]
246
- )
247
-
248
- gpt_response = response.choices[0].message["content"]
249
-
250
- tokens_used = response.usage
251
- question_cost = (tokens_used.get('total_tokens', 0) / 1000) * .03
252
- prompt_tokens = tokens_used.get('prompt_tokens',)
253
- completion_tokens = tokens_used.get('completion_tokens', 0)
254
- end_time = datetime.datetime.now()
255
- response_time = end_time - start_time
256
-
257
- append_to_at_qalog(your_role, school_selection, output_format, input_text, gpt_response,response_time,question_cost,prompt_tokens,completion_tokens)
258
-
259
- return response_label,gpt_response
260
-
261
- def log_login(username):
262
-
263
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{user_log_table_name}'
264
-
265
- # Organize data for Airtable
266
- new_fields = {
267
- 'user_name': str(username),
268
- }
269
-
270
- data = {
271
- 'fields': new_fields
272
- }
273
-
274
- try:
275
- # Post data to Airtable
276
- response = requests.post(AIRTABLE_ENDPOINT, headers=HEADERS, json=data)
277
-
278
- # Check for errors
279
- response.raise_for_status()
280
-
281
- except requests.exceptions.HTTPError as http_error:
282
- # Handle the HTTP error (e.g., log it or display an error message)
283
- print(f"HTTP error occurred: {http_error}")
284
-
285
- except Exception as e:
286
- # Handle exceptions, log errors, or raise them as needed
287
- print(f"An error occurred: {str(e)}")
288
-
289
- def login_auth(username, password):
290
-
291
- AIRTABLE_ENDPOINT = f'https://api.airtable.com/v0/{base_id}/{users_table_name}'
292
-
293
- # Query the 'users' table to check for a match with the provided username and password
294
- params = {
295
- 'filterByFormula': f'AND(user_name = "{username}", password = "{password}")'
296
- }
297
-
298
- response = requests.get(AIRTABLE_ENDPOINT, headers=HEADERS, params=params)
299
-
300
- if response.status_code == 200:
301
- data = response.json()
302
- if data.get('records'):
303
-
304
- log_login(username)
305
- global logged_in_user
306
- logged_in_user = username
307
-
308
- return True
309
-
310
- print(f"Invalid user/password combination")
311
-
312
- return False
313
-
314
- #Gradio UI
315
- CIMStheme = gr.themes.Soft().set(button_primary_background_fill='#6562F4')
316
-
317
- # Initialize an empty list to store the examples
318
- ui_examples = []
319
- school_selection = []
320
-
321
- schools = get_schools()
322
-
323
- get_examples()
324
-
325
- with gr.Blocks(CIMStheme) as iface:
326
- with gr.Row():
327
- with gr.Column(scale=2):
328
- gr.Image(label="Logo",value="CIMS Logo Purple.png",width=10,show_download_button=False,interactive=False,show_label=False,elem_id="logo",container=False)
329
- with gr.Column(scale=2):
330
- gr.Markdown(value="# NILI - Powered by CIMS.AI")
331
- with gr.Column(scale=2):
332
- gr.Markdown("")
333
- with gr.Row():
334
- with gr.Column():
335
- gr.Interface(fn=chatbot,
336
- inputs=[
337
- gr.components.Dropdown(["Student Athlete","Parent","Athletic Director"],multiselect=False,info="Select a role.",label="User Role", ),
338
- gr.components.Dropdown(schools,multiselect=True,info="Select one or more schools. This will help set the context of your question.",label="School Context"),
339
- gr.components.Dropdown(["Summary","Detailed Analysis","Table"],multiselect=False,info="Select the desired output format.",label="Output Format"),
340
- gr.components.Textbox(lines=5, placeholder="Enter your question here", label="NIL Question")],
341
- outputs=[
342
- gr.components.Markdown(response_label),
343
- gr.components.HTML(label="NILI Response")
344
- ],
345
- description="Ask any question about Name, Image, Likeness (NIL)",
346
- allow_flagging="manual",
347
- examples=ui_examples,
348
- cache_examples = False,
349
- flagging_options=["The response is incorrect","The response is inappropriate","The response doesn't make sense"]
350
- )
351
- with gr.Row():
352
- with gr.Column():
353
- gr.HTML('<center><i>CIMS.AI Confidential 2023</i></center>')
354
-
355
- iface.launch(auth=login_auth, auth_message= "Enter your username and password that you received from CIMS.AI. To request a login, please email '[email protected]'")
356
- #iface.launch(auth=('admin','cims.ai'))