datasaur-dev commited on
Commit
9bb28d5
·
verified ·
1 Parent(s): 017e4bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -32
app.py CHANGED
@@ -5,48 +5,55 @@ import re
5
 
6
  # WARNING: It is not recommended to hardcode sensitive data like API tokens in code.
7
  # Consider using environment variables or other secure methods for production applications.
8
- API_URL = "https://deployment.datasaur.ai/api/deployment/8/2723/chat/completions"
9
  API_TOKEN = os.environ["DATASAUR_API_KEY"]
10
 
11
  import re
12
  import json
13
 
14
- def extract_suggestion_value(text):
15
  """
16
- Extracts the value of the 'suggestion' key from a given string that may contain JSON-like content.
 
17
 
18
  Parameters:
19
- text (str): Input text containing a JSON-like 'suggestion' field.
20
 
21
  Returns:
22
- dict: Dictionary with the 'suggestion' key and its extracted value, or None if not found.
23
  """
24
  # First, try to directly parse as JSON
25
  try:
26
  parsed = json.loads(text)
27
- if "suggestion" in parsed:
28
- return parsed["suggestion"]
29
  except json.JSONDecodeError:
30
  pass # Fall back to regex if not valid JSON
31
 
32
- # Fallback: use regex to extract suggestion value
33
- match = re.search(r'"suggestion"\s*:\s*"([^"]+)"', text)
34
  if match:
35
- return match.group(1)
 
 
 
 
 
 
36
 
37
  return None
38
 
39
 
40
  def magic_function(input_text):
41
  """
42
- Sends text to the Datasaur deployment API and returns the processed text.
43
  """
44
  headers = {
45
  "Content-Type": "application/json",
46
  "Authorization": f"Bearer {API_TOKEN}",
47
  }
48
  data = {
49
- "messages": [{"role": "user", "content": f"Input: `{input_text}`"}]
50
  }
51
 
52
  try:
@@ -59,38 +66,59 @@ def magic_function(input_text):
59
  # This may need adjustment if the API has a different format.
60
  content = response_json.get("choices", [{}])[0].get("message", {}).get("content", "Error: Could not parse response.")
61
 
62
- content = extract_suggestion_value(content)
63
-
64
- return content.strip()
 
 
 
65
 
66
  except requests.exceptions.RequestException as e:
67
- return f"API Request Error: {e}"
68
  except (ValueError, KeyError, IndexError):
69
  # Handle cases where response is not valid JSON or structure is unexpected
70
- return f"Error processing API response: {response.text}"
71
 
72
- def handle_magic_click(current_text):
73
  """
74
  When the magic button is clicked, this function gets the improved text,
75
  and returns the new and previous text to update the UI.
76
- If the improved text has no "[" or "]" characters, make text area light green and hide previous text.
77
  """
78
- improved_text = magic_function(current_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- # Check if improved text contains "[" or "]"
81
- if "[" not in improved_text and "]" not in improved_text:
82
- # No brackets found - make text area light green and hide previous text
83
  return (
84
- gr.update(value=improved_text, elem_classes="success-text"),
85
- current_text,
86
- gr.update(visible=False)
 
 
 
87
  )
88
  else:
89
- # Brackets found - reset text area to normal appearance and show previous text
90
  return (
91
- gr.update(value=improved_text, elem_classes=""),
92
- current_text,
93
- gr.update(visible=True)
 
 
 
94
  )
95
 
96
 
@@ -102,11 +130,12 @@ with gr.Blocks(css=".success-text { background-color: #d4edda !important; }") as
102
  previous_text_area = gr.Textbox(label="Previous Text", lines=5, visible=False)
103
  with gr.Column(scale=1):
104
  magic_button = gr.Button("Magic Button")
 
105
 
106
  magic_button.click(
107
  fn=handle_magic_click,
108
- inputs=text_area,
109
- outputs=[text_area, previous_text_area, previous_text_area]
110
  )
111
 
112
  if __name__ == "__main__":
 
5
 
6
  # WARNING: It is not recommended to hardcode sensitive data like API tokens in code.
7
  # Consider using environment variables or other secure methods for production applications.
8
+ API_URL = "https://deployment.datasaur.ai/api/deployment/8/2738/chat/completions"
9
  API_TOKEN = os.environ["DATASAUR_API_KEY"]
10
 
11
  import re
12
  import json
13
 
14
+ def extract_json_from_text(text):
15
  """
16
+ Extracts JSON content from text that starts with { and ends with }.
17
+ Returns the parsed JSON object with category_fix and suggestion keys.
18
 
19
  Parameters:
20
+ text (str): Input text that may contain JSON content.
21
 
22
  Returns:
23
+ dict: Dictionary with 'category_fix' and 'suggestion' keys, or None if not found.
24
  """
25
  # First, try to directly parse as JSON
26
  try:
27
  parsed = json.loads(text)
28
+ if "category_fix" in parsed and "suggestion" in parsed:
29
+ return parsed
30
  except json.JSONDecodeError:
31
  pass # Fall back to regex if not valid JSON
32
 
33
+ # Fallback: use regex to extract JSON content between { and }
34
+ match = re.search(r'\{[^{}]*\}', text)
35
  if match:
36
+ try:
37
+ json_str = match.group(0)
38
+ parsed = json.loads(json_str)
39
+ if "category_fix" in parsed and "suggestion" in parsed:
40
+ return parsed
41
+ except json.JSONDecodeError:
42
+ pass
43
 
44
  return None
45
 
46
 
47
  def magic_function(input_text):
48
  """
49
+ Sends text to the Datasaur deployment API and returns the processed JSON with category_fix and suggestion.
50
  """
51
  headers = {
52
  "Content-Type": "application/json",
53
  "Authorization": f"Bearer {API_TOKEN}",
54
  }
55
  data = {
56
+ "messages": [{"role": "user", "content": f"Time Entry Input: `{input_text}`"}]
57
  }
58
 
59
  try:
 
66
  # This may need adjustment if the API has a different format.
67
  content = response_json.get("choices", [{}])[0].get("message", {}).get("content", "Error: Could not parse response.")
68
 
69
+ result = extract_json_from_text(content)
70
+
71
+ if result:
72
+ return result
73
+ else:
74
+ return {"category_fix": "ERROR", "suggestion": "Could not parse response"}
75
 
76
  except requests.exceptions.RequestException as e:
77
+ return {"category_fix": "ERROR", "suggestion": f"API Request Error: {e}"}
78
  except (ValueError, KeyError, IndexError):
79
  # Handle cases where response is not valid JSON or structure is unexpected
80
+ return {"category_fix": "ERROR", "suggestion": f"Error processing API response: {response.text}"}
81
 
82
+ def handle_magic_click(current_text, current_button_text):
83
  """
84
  When the magic button is clicked, this function gets the improved text,
85
  and returns the new and previous text to update the UI.
86
+ If category_fix == "COMPLIANT", make text area light green, hide previous text, lock text area, and change button to Reset.
87
  """
88
+ if current_button_text == "Reset":
89
+ # Reset to initial state
90
+ return (
91
+ gr.update(value="", elem_classes="", interactive=True), # text_area - reset and unlock
92
+ "", # previous_text_area - clear
93
+ gr.update(visible=False), # previous_text_area visibility - hide
94
+ gr.update(value="", visible=False), # category_label - hide
95
+ gr.update(value="Magic Button"), # button text - reset
96
+ "Your Text" # text_area label - reset
97
+ )
98
+
99
+ result = magic_function(current_text)
100
+ category_fix = result.get("category_fix", "")
101
+ suggestion = result.get("suggestion", "")
102
 
103
+ if category_fix == "COMPLIANT":
104
+ # COMPLIANT case - no changes to input, green background, lock, add checklist, change button to Reset
 
105
  return (
106
+ gr.update(value=current_text, elem_classes="success-text", interactive=False), # text_area - keep original, green, lock
107
+ current_text, # previous_text_area - store current
108
+ gr.update(visible=False), # previous_text_area visibility - hide
109
+ gr.update(value=f"**{category_fix}**", visible=True), # category_label - show category in bold
110
+ gr.update(value="Reset"), # button text - change to Reset
111
+ "Your Text ✓" # text_area label - add checklist symbol
112
  )
113
  else:
114
+ # Non-compliant case - show suggestion, show previous text, show category
115
  return (
116
+ gr.update(value=suggestion, elem_classes="", interactive=True), # text_area - show suggestion, normal style, unlocked
117
+ current_text, # previous_text_area - store current
118
+ gr.update(visible=True), # previous_text_area visibility - show
119
+ gr.update(value=f"**{category_fix}**", visible=True), # category_label - show category in bold
120
+ gr.update(value="Magic Button"), # button text - keep as Magic Button
121
+ "Your Text" # text_area label - normal
122
  )
123
 
124
 
 
130
  previous_text_area = gr.Textbox(label="Previous Text", lines=5, visible=False)
131
  with gr.Column(scale=1):
132
  magic_button = gr.Button("Magic Button")
133
+ category_label = gr.Markdown("", visible=False)
134
 
135
  magic_button.click(
136
  fn=handle_magic_click,
137
+ inputs=[text_area, magic_button],
138
+ outputs=[text_area, previous_text_area, previous_text_area, category_label, magic_button, text_area]
139
  )
140
 
141
  if __name__ == "__main__":