import gradio as gr import requests import os import re # WARNING: It is not recommended to hardcode sensitive data like API tokens in code. # Consider using environment variables or other secure methods for production applications. API_URL = "https://deployment.datasaur.ai/api/deployment/8/2723/chat/completions" API_TOKEN = os.environ["DATASAUR_API_KEY"] import re import json def extract_suggestion_value(text): """ Extracts the value of the 'suggestion' key from a given string that may contain JSON-like content. Parameters: text (str): Input text containing a JSON-like 'suggestion' field. Returns: dict: Dictionary with the 'suggestion' key and its extracted value, or None if not found. """ # First, try to directly parse as JSON try: parsed = json.loads(text) if "suggestion" in parsed: return parsed["suggestion"] except json.JSONDecodeError: pass # Fall back to regex if not valid JSON # Fallback: use regex to extract suggestion value match = re.search(r'"suggestion"\s*:\s*"([^"]+)"', text) if match: return match.group(1) return None def magic_function(input_text): """ Sends text to the Datasaur deployment API and returns the processed text. """ headers = { "Content-Type": "application/json", "Authorization": f"Bearer {API_TOKEN}", } data = { "messages": [{"role": "user", "content": f"Input: `{input_text}`"}] } try: response = requests.post(API_URL, headers=headers, json=data) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) response_json = response.json() # Extract content from a standard chat completion response structure. # This may need adjustment if the API has a different format. content = response_json.get("choices", [{}])[0].get("message", {}).get("content", "Error: Could not parse response.") content = extract_suggestion_value(content) return content.strip() except requests.exceptions.RequestException as e: return f"API Request Error: {e}" except (ValueError, KeyError, IndexError): # Handle cases where response is not valid JSON or structure is unexpected return f"Error processing API response: {response.text}" def handle_magic_click(current_text): """ When the magic button is clicked, this function gets the improved text, and returns the new and previous text to update the UI. If the improved text has no "[" or "]" characters, make text area light green and hide previous text. """ improved_text = magic_function(current_text) # Check if improved text contains "[" or "]" if "[" not in improved_text and "]" not in improved_text: # No brackets found - make text area light green and hide previous text return ( gr.update(value=improved_text, elem_classes="success-text"), current_text, gr.update(visible=False) ) else: # Brackets found - keep normal behavior return improved_text, current_text, gr.update(visible=True) with gr.Blocks(css=".success-text { background-color: #d4edda !important; }") as demo: gr.Markdown("# Time Entry Improvement") with gr.Row(): with gr.Column(scale=4): text_area = gr.Textbox(label="Your Text", lines=5) previous_text_area = gr.Textbox(label="Previous Text", lines=5, visible=False) with gr.Column(scale=1): magic_button = gr.Button("Magic Button") magic_button.click( fn=handle_magic_click, inputs=text_area, outputs=[text_area, previous_text_area, previous_text_area] ) if __name__ == "__main__": demo.launch()