Spaces:
Running
Running
File size: 22,559 Bytes
871b8ae |
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
import openai
import gradio as gr
import uuid
import time
import IPython
from playsound import playsound
import threading
from scipy.io import wavfile
#tts = TTS(model_name="tts_models/multilingual/multi-dataset/your_tts", progress_bar=False)#.to("cuda")
conv_uuid = str(uuid.uuid4())
import os
# Replace with your key
# openai.api_key = os.getenv('openai_api')
seller_prompt_path = "./prompts/seller_prompt_no_meat.txt"
extras_for_senior = """
Cybersecurity Incident: During the negotiation of the Letter of Intent, the seller disclosed that there was a breach in their customer data. Email addresses from the customer’s data that was exposed totalled no more than 200. No other personal identifiable information was exfiltrated. That client has since filed a claim requesting for compensation related to damages from this breach. TechEase has disclosed the privacy breach to its customer base, has taken remedial action to prevent another breach and correct the security weaknesses in its infrastructure, and has complied with all relevant regulatory requirements concerning the breach.
"""
extras_for_partner = """
Multiple Cybersecurity Breaches/Weak security infrastructure
Your associate had just informed you of the current status of the deal:
Quasi-fundamental reps and warranties related to cybersecurity, IP, and privacy are already set up
Special indemnities are also already set up for cybersecurity and privacy
TechEase has cybersecurity and privacy insurance
Recently, new problems have come up with TechEase, and we need your expertise to renegotiate
TechEase’s AI platform has unique product functionalities and a fast-growing customer base. Security infrastructure is not its focus. Accordingly, there are key issues to be discussed with regards to infiltrations into its system and what type of information technology security infrastructure is in place. TechEase just advised ShopMaster of multiple occurrences of prior breaches to its security infrastructure and it does not know what data, if any, was exfiltrated. Several clients have just switched to TechEase’s competitors given the historical weaknesses of its security infrastructure. Most clients, though, are still enthusiastic about continuous improvements of its core AI product. TechEase has also disclosed the security breaches to its customer base, and has taken remedial action to prevent another breach. However, TechEase does not have the talent to investigate the root causes behind multiple breaches. ShopMaster is deeply concerned and wants to drop the deal. However, ShopMaster is still interested in TechEase’s AI platform, but does not want to deal with the security issues related to the company.
"""
with open(seller_prompt_path, 'r') as f:
seller_prompt = f.read()
seller_prompt_path_markdown = "./prompts/seller_prompt_no_meat_markdown.txt"
with open(seller_prompt_path_markdown, 'r') as f:
seller_prompt_markdown = f.read()
seller_meat_1 = "./prompts/seller_meat_1.txt"
with open(seller_meat_1, 'r') as f:
seller_meat_1 = f.read()
seller_meat_1_markdown = "./prompts/seller_meat_1_markdown.txt"
with open(seller_meat_1_markdown, 'r') as f:
seller_meat_1_markdown = f.read()
hint_counter = 0
initial_prompt = os.getenv("system_prompt")
#def play_sound_in_background():
# playsound("output.wav")
def predict(message, history, username, bdi_checkbox_value, api_box):
global initial_prompt
openai.api_key = api_box
chatinterface.additional_inputs[0].value = username
history_openai_format = []
if level_dropdown.value == 'Senior':
initial_prompt += extras_for_senior
elif level_dropdown.value == 'Partner':
initial_prompt += extras_for_partner
history_openai_format.append(
{"role": "system", "content": initial_prompt.replace("Philip", name_box.value)})
for human, assistant in history:
history_openai_format.append({"role": "user", "content": human})
history_openai_format.append(
{"role": "assistant", "content": assistant})
history_openai_format.append({"role": "user", "content": message})
response = openai.ChatCompletion.create(
model='gpt-4o',
messages=history_openai_format,
temperature=0.8,
stream=True
)
partial_message = ""
print(bdi_checkbox_value)
for chunk in response:
if len(chunk['choices'][0]['delta']) != 0:
partial_message = partial_message + \
chunk['choices'][0]['delta']['content']
user_name_no_space = username.replace(" ","_")
file_name = f"{user_name_no_space}_{conv_uuid}.txt"
if bdi_checkbox_value:
# save user history and new text with username.txt
with open(file_name, "a") as f:
f.write(f"User: {message}\n")
f.write(f"Assistant: {partial_message}\n")
# before returning let's save an audio and play it
# tts.tts_to_file(partial_message, speaker_wav="/home/hammh0a/Downloads/New Recording 2 (1).wav", language="en", file_path="output.wav")
# threading.Thread(target=play_sound_in_background, args=(), daemon=True).start()
# audio_button.value = "output.wav"
return partial_message
else:
# save user history and new text with username.txt
remove_bdi = partial_message.split("Response:")[-1]
try:
with open(file_name, "a") as f:
f.write(f"User: {message}\n")
f.write(f"Assistant: {partial_message}\n")
except:
pass
# tts.tts_to_file(remove_bdi, speaker_wav="/home/hammh0a/Downloads/New Recording 2 (1).wav", language="en", file_path="output.wav")
# threading.Thread(target=play_sound_in_background, args=(), daemon=True).start()
# audio_button.value = "output.wav"
return remove_bdi
#def read_audio_again(audio_button):
# return wavfile.read("output.wav")
# gr.ChatInterface(predict).queue().launch()
def vote(data: gr.LikeData):
if data.liked:
print("You upvoted this response: " + data.value)
else:
print("You downvoted this response: " + data.value)
def update_name(name):
# This function will be called when the user types in the name_box
return name
negotiation_areas = {
"Junior": "(1) Defining type of representations and warranties (fundamental, general and possibly quasi). \n(2) [More Advanced, Second-Layer Negotiation]:Setting parameters of liability. \n(3)Survival period, cap on liability, and basket.",
"Senior": "(1) Mitigation of the incident (i.e. known risk): indemnification clause (e.g. survival period, cap, holdback, basket). \n(2) Managing vulnerability exposed (i.e. unknown risk): renegotiation of reps and warranties regarding cybersecurity and privacy ",
"Partner": "Deal Structure"
}
# def issue_change(rs):
# return gr.update(choices=general_issues[rs], value=None)
# def update_textbox_issues(issue_selection):
# issue_textbox.value = specific_issues.get(issue_selection, "Invalid Selection")
# issue_dropdown.value = issue_selection
# return specific_issues.get(issue_selection, "Invalid Selection")
def update_incident(selection):
if selection == "Junior":
markdown_incident.value = ""
elif selection == "Senior":
markdown_incident.value ="""During the negotiation of the Letter of Intent, the seller disclosed that there was a breach in their customer data. Email addresses from the customer’s data that was exposed totalled no more than 200. No other personal identifiable information was exfiltrated. That client has since filed a claim requesting for compensation related to damages from this breach. TechEase has disclosed the privacy breach to its customer base, has taken remedial action to prevent another breach and correct the security weaknesses in its infrastructure, and has complied with all relevant regulatory requirements concerning the breach. """
elif selection == "Partner":
markdown_incident.value = """Multiple Cybersecurity Breaches/Weak security infrastructure
Your associate had just informed you of the current status of the deal:
Quasi-fundamental reps and warranties related to cybersecurity, IP, and privacy are already set up
Special indemnities are also already set up for cybersecurity and privacy
TechEase has cybersecurity and privacy insurance
Recently, new problems have come up with TechEase, and we need your expertise to renegotiate
TechEase’s AI platform has unique product functionalities and a fast-growing customer base. Security infrastructure is not its focus. Accordingly, there are key issues to be discussed with regards to infiltrations into its system and what type of information technology security infrastructure is in place. TechEase just advised ShopMaster of multiple occurrences of prior breaches to its security infrastructure and it does not know what data, if any, was exfiltrated. Several clients have just switched to TechEase’s competitors given the historical weaknesses of its security infrastructure. Most clients, though, are still enthusiastic about continuous improvements of its core AI product. TechEase has also disclosed the security breaches to its customer base, and has taken remedial action to prevent another breach. However, TechEase does not have the talent to investigate the root causes behind multiple breaches. ShopMaster is deeply concerned and wants to drop the deal. However, ShopMaster is still interested in TechEase’s AI platform, but does not want to deal with the security issues related to the company.
"""
if selection == "Junior":
return gr.Textbox.update(visible = False)#markdown_incident.value
else:
return gr.Textbox.update(value = markdown_incident.value, visible = True)
def update_markdown_notice(selection):
if selection == "Junior":
markdown_notice.value = seller_meat_1_markdown
elif selection == "Senior":
markdown_notice.value = seller_meat_1_markdown
elif selection == "Partner":
markdown_notice.value = ""
return markdown_notice.value
# Step 1 - Based on the level of the user, display the main focus
def update_textbox_focuses(selection):
global hint_counter
hint_counter = 0 # Reset the hint counter
focuses = {
"Junior": "Types of representations and warranties.",
"Senior": "Cybersecurity incident.",
"Partner": "Multiple Cybersecurity Breaches/Weak security infrastructure.",
}
main_focus_textbox.value = focuses.get(selection, "Invalid selection")
return focuses.get(selection, "Invalid selection")
# Step 2 - Based on the main focus, display suggested areas of negotiation.
def update_textbox_negotiation_options(selection):
negotiation_areas_textbox.value = negotiation_areas.get(selection, "Invalid selection")
level_dropdown.value = selection
return negotiation_areas.get(selection, "Invalid selection")
# def update_textbox_disussion_options(selection):
# print(selection)
# discussion_options = {
# "Focus 1": "This is discussion option 1. \nThis is discussion option 2. ",
# "Focus 2": "This is discussion option 3. \nThis is discussion option 4.",
# "Focus 3": "This is discussion option 5. \nThis is discussion option 6.",
# "Focus 4": "This is discussion option 7. \nThis is discussion option 8.",
# }
# options.value = discussion_options.get(selection, "Invalid selection")
# main_focus_dropdown.value = selection
# return discussion_options.get(selection, "Invalid selection")
hints = {
"Junior": ["Hint 1: Remember the highlighted risk factors!", 'Sample Prompt 1: We propose the fundamental representations and warranties will include IP, cybersecurity, data privacy, regulatory/compliance, employee health and benefits, in addition to the traditional fundamental categories.', 'Sample Prompt 2: We propose the survival period for general representations to be set at 3 years.', 'Sample Prompt 3: We propose the cap on liability for general representations to be set at 50% of purchase Price with a 0.25% tipping basket.', 'Sample Prompt 4: We propose the cap on liability for fundamental representations to be set at 100% of purchase price with full duration of the statute of limitations and no basket.'],
"Senior": ['Hint 1: Consider there are two types of risks (known, unknown) that require mitigation.', "Hint 2: Recall distinction between standalone indemnities and reps and warranties.", "Hint 3: Recall there are different levels of reps and warranties which trigger different levels of protection.", "Hint 4: Consider elevating cybersecurity and privacy reps and warranties to fundamental."],
"Partner": ["No hints available for partners."]
}
def hint_click():
global hint_counter
# if level is junior then we have two hints else if senior only one hint and partner nothing.
if hint_counter == 0 and level_dropdown.value == "Junior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[0]
elif hint_counter == 1 and level_dropdown.value == "Junior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[1]
elif hint_counter == 2 and level_dropdown.value == "Junior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[2]
elif hint_counter == 3 and level_dropdown.value == "Junior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[3]
elif hint_counter == 4 and level_dropdown.value == "Junior":
hint_counter +=1
hint_textbox.value = hints.get(level_dropdown.value)[4]
elif hint_counter == 5 and level_dropdown.value == "Junior":
hint_counter = 0
hint_textbox.value = "No more hints available for this level."
elif hint_counter == 0 and level_dropdown.value == "Senior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[0]
elif hint_counter == 1 and level_dropdown.value == "Senior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[1]
elif hint_counter == 2 and level_dropdown.value == "Senior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[2]
elif hint_counter == 3 and level_dropdown.value == "Senior":
hint_counter += 1
hint_textbox.value = hints.get(level_dropdown.value)[3]
elif hint_counter == 4 and level_dropdown.value == "Senior":
hint_counter = 0
hint_textbox.value = "No more hints available for this level."
elif level_dropdown.value == "Partner":
hint_textbox.value = "No hints available for partners."
return hint_textbox.value
with gr.Blocks(theme=gr.themes.Soft()) as demo:
with gr.Tab("Documentation"):
header = gr.Markdown()
header.value = """
<div style="border: 1px solid #ccc; box-shadow: 0 2px 5px rgba(0,0,0,0.2); background-color: #ffffff; padding: 15px; border-radius: 5px; margin: 10px 0;">
<p align="center">
<img src="https://i.ibb.co/H2b3PFZ/New-Project-1.jpg" alt="TechEase Logo" width="50%" height="auto"/>
</p>
"""
documentation = gr.Markdown()
with open("./prompts/documentation_markdown.txt", "r") as f:
documentation.value = f.read()
with gr.Tab("App"):
header = gr.Markdown()
header.value = """
<div style="border: 1px solid #ccc; box-shadow: 0 2px 5px rgba(0,0,0,0.2); background-color: #ffffff; padding: 15px; border-radius: 5px; margin: 10px 0;">
<p align="center">
<img src="https://i.ibb.co/H2b3PFZ/New-Project-1.jpg" alt="TechEase Logo" width="50%" height="auto"/>
</p>
"""
system_message = gr.Markdown()
system_message.value = """
<div style="background-color: #e9eeff; border: 2px solid black; box-shadow: 5px 5px 10px grey; padding: 15px; border-radius: 10px; font-family: 'Arial', sans-serif;">
## Initial Setup
### Parties and Background:
**Seller:** TechEase, Inc. is a privately-owned corporation that has developed and commercializes a proprietary SaaS solution for SMB retailers (small public facing businesses, like restaurants, antique shops, gift shops, etc.,that carry physical inventory)which manages all aspects of the clients’ Point of Sales (POS) activities, including customer registration, online ordering and shipping logistics. TechEase’s platform interacts directly with the retail public and retrieves, assembles and stores credit card and other sensitive personal information from the retail customers. TechEase has two owners.
**Buyer:** ShopMaster, Inc. plans to acquire TechEase, Inc. via an equity sale.The owners of TechEase will sell their shares of stock to ShopMaster. ShopMaster prefers the equity acquisition structure because it is less disruptive to Intellectual Property (IP), employee relationships, and existing client contracts, and will yield a more favorable tax outcome for the owners.
---
### Scenario:
ShopMaster, Inc. has identified TechEase, Inc. as a strategic acquisition target to extend its market presence and technology capabilities. The planned structure of the acquisition is an equity sale by the two owners. As the transaction is structured as an equity sale, ShopMaster, Inc. would become the new owner of TechEase. TechEase would become a wholly-owned subsidiary of ShopMaster. TechEase would remain in operation. This means that all liabilities of TechEase would stay in place (both known and unknown).
Because the TechEase platform interacts directly with the retail public, and stores sensitive customer information, ShopMaster is especially concerned about risks related to cyber security breaches and data privacy. Incidents or deficiencies in these areas could create massive legal and regulatory exposure for ShopMaster and potentially jeopardize the viability of the acquisition.
</div>
"""
# User puts in their name
name_box = gr.Textbox(
label="Name", placeholder="Your name here", interactive=True)
api_box = gr.Textbox(
label="OpenAI API Key", placeholder="sk-", interactive=True, type='password')
# Level Dropdown - Select the level of the user
level_dropdown = gr.Dropdown(
choices=["Junior", "Senior", "Partner"], label="Please Select Level", interactive=True)
# If Junior or Senior, display the seller_prompt_markdown
markdown_notice = gr.Markdown()
level_dropdown.change(fn=update_markdown_notice, inputs=[level_dropdown], outputs=[markdown_notice])
markdown_meat = gr.Markdown()
# markdown_meat.value = seller_meat_1_markdown
# Based on the Level - Display the Main Focus
main_focus_textbox = gr.Textbox(label="Main Focus")
level_dropdown.change(fn=update_textbox_focuses, inputs=[level_dropdown], outputs=[main_focus_textbox])
markdown_incident = gr.Textbox(label="Incident", visible=False)
level_dropdown.change(fn=update_incident, inputs=[level_dropdown], outputs=[markdown_incident])
# Based on level - Display the suggested areas of negotiation
negotiation_areas_textbox = gr.Textbox(label="Suggested Areas of Negotiation")
level_dropdown.change(fn=update_textbox_negotiation_options, inputs=[level_dropdown], outputs=[negotiation_areas_textbox])
# Create a button that displays hints when clicked.
hint_button = gr.Button(value="Hint", interactive=True)
hint_textbox = gr.Textbox(label="Hint")
hint_button.click(hint_click, outputs=hint_textbox)
# suggested_prompt_textbox = gr.Textbox(label="Suggested Prompt")
# hint_button.click(fn=hint_click, outputs=[suggested_prompt_textbox])
# Add a text reminder on the rules of the game, color text in red
markdown_rules = gr.Markdown()
markdown_rules.value = """
<div style="background-color: #fedfc9; border: 2px solid black; box-shadow: 5px 5px 10px grey; padding: 15px; border-radius: 10px; font-family: 'Arial', sans-serif;">
<h2>Reminder</h2>
<p>Your goal is to negotiate the most beneficial deal for your client and to properly assess the scope.</p>
</div>
"""
# define checkbox
bdi_checkbox = gr.Checkbox(label="BDI", value=True, interactive=True)
# rules = gr.Textbox(
# label="Rules", value="Your goal is to extract facts that would allow you to choose the right legal tools needed in your term sheet", placeholder="Reminder!", interactive=False)
# # Select an issue
# issue_dropdown = gr.Dropdown(
# choices=["Issue 1", "Issue 2"], label="Please Select An Issue")
# issue_textbox = gr.Textbox(label="Selected Issue")
# issue_dropdown.change(fn=update_textbox_issues, inputs=issue_dropdown, outputs=issue_textbox)
# level_dropdown.change(fn=issue_change, inputs=[level_dropdown], outputs=[issue_dropdown])
# # Select main focus
# main_focus_dropdown = gr.Dropdown(
# choices=["Focus 1", "Focus 2"], label="Please Select Main Focus", interactive=True)
# Options for Discussion - Textbox Display
# options = gr.Textbox(label="Options for Discussion", placeholder="Options for Discussion", interactive=True)
# main_focus_dropdown.change(fn=update_textbox_disussion_options, inputs=[main_focus_dropdown], outputs=[options])
# # Hint Button - If clicked create a counter to reveal the next hint
# hint_button = gr.Button(value="Hint", label="Hint", interactive=True)
# hint_textbox = gr.Textbox(label="Hint")
# hint_button.click(hint_click, outputs=hint_textbox)
chatinterface = gr.ChatInterface(
predict, additional_inputs=[name_box, bdi_checkbox, api_box])
chatinterface.chatbot.avatar_images = ["https://law.stanford.edu/wp-content/uploads/2021/09/auto-draft-393-400x400.jpg",
"https://scalebranding.com/wp-content/uploads/2022/02/Cute-Robot-Diver-Logo.png"]
chatinterface.chatbot.show_copy_button = True
chatinterface.chatbot.height = "750px"
# audio button
#audio_button = gr.Audio(value="/home/hammh0a/Downloads/ui_bargain/output.wav", label="Audio", interactive=True, autoplay=True)
#audio_button.pause(read_audio_again, inputs = [audio_button], outputs = [audio_button])
demo.queue().launch(share=True)
|