File size: 2,861 Bytes
cb4d130
749c207
a6fdb22
e274157
a6fdb22
749c207
 
b6954d6
c3cb308
cb4d130
ecf8f43
 
 
 
 
 
 
 
 
749c207
 
 
 
 
 
 
 
 
b6954d6
749c207
 
 
 
 
 
 
 
 
 
 
e274157
ecf8f43
 
 
749c207
 
 
 
 
 
 
cabc6e8
 
 
 
 
 
 
 
 
749c207
 
b6013aa
a6fdb22
cabc6e8
1f2d6db
 
a6fdb22
 
749c207
 
cabc6e8
749c207
cabc6e8
749c207
 
 
 
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
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"]

def extract_suggestion_with_regex(xml_string):
    """Extract content of <suggestion> tag using regex."""
    pattern = r"<suggestion>(.*?)</suggestion>"
    match = re.search(pattern, xml_string, re.DOTALL)
    if match:
        return match.group(1).strip()
    else:
        raise ValueError("No <suggestion> tag found")
        
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_with_regex(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.
    It also makes the "Previous Text" box visible.
    """
    improved_text = magic_function(current_text)
    return improved_text, current_text, gr.update(visible=True)


with gr.Blocks() 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()