ofermend commited on
Commit
243d63b
1 Parent(s): 9b43a21

added utils

Browse files
Files changed (1) hide show
  1. utils.py +74 -0
utils.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import json
4
+ import re
5
+
6
+ import streamlit as st
7
+
8
+ from langdetect import detect_langs
9
+ from langcodes import Language
10
+
11
+ headers = {
12
+ 'Content-Type': 'application/json',
13
+ 'Accept': '*/*'
14
+ }
15
+
16
+ def identify_language(response):
17
+ lang_code = detect_langs(response)[0].lang
18
+ return Language.make(language=lang_code).display_name()
19
+
20
+ def thumbs_feedback(feedback, **kwargs):
21
+ """
22
+ Sends feedback to Amplitude Analytics
23
+ """
24
+ send_amplitude_data(
25
+ user_query=kwargs.get("user_query", "No user input"),
26
+ bot_response=kwargs.get("bot_response", "No bot response"),
27
+ demo_name=kwargs.get("demo_name", "Unknown"),
28
+ feedback=feedback['score'],
29
+ )
30
+ st.session_state.feedback_key += 1
31
+
32
+ def send_amplitude_data(user_query, bot_response, demo_name, feedback=None):
33
+ # Send query and response to Amplitude Analytics
34
+ data = {
35
+ "api_key": os.getenv('AMPLITUDE_TOKEN'),
36
+ "events": [{
37
+ "device_id": st.session_state.device_id,
38
+ "event_type": "submitted_query",
39
+ "event_properties": {
40
+ "Space Name": demo_name,
41
+ "Demo Type": "Agent",
42
+ "query": user_query,
43
+ "response": bot_response,
44
+ "Response Language": identify_language(bot_response)
45
+ }
46
+ }]
47
+ }
48
+ if feedback:
49
+ data["events"][0]["event_properties"]["feedback"] = feedback
50
+
51
+ response = requests.post('https://api2.amplitude.com/2/httpapi', headers=headers, data=json.dumps(data))
52
+ if response.status_code != 200:
53
+ print(f"Amplitude request failed with status code {response.status_code}. Response Text: {response.text}")
54
+
55
+ def escape_dollars_outside_latex(text):
56
+ # Define a regex pattern to find LaTeX equations (either single $ or double $$)
57
+ pattern = re.compile(r'(\$\$.*?\$\$|\$.*?\$)')
58
+ latex_matches = pattern.findall(text)
59
+
60
+ # Placeholder to temporarily store LaTeX equations
61
+ placeholders = {}
62
+ for i, match in enumerate(latex_matches):
63
+ placeholder = f'__LATEX_PLACEHOLDER_{i}__'
64
+ placeholders[placeholder] = match
65
+ text = text.replace(match, placeholder)
66
+
67
+ # Escape dollar signs in the rest of the text
68
+ text = text.replace('$', '\\$')
69
+
70
+ # Replace placeholders with the original LaTeX equations
71
+ for placeholder, original in placeholders.items():
72
+ text = text.replace(placeholder, original)
73
+ return text
74
+