datasaur-dev's picture
Update app.py
a6fdb22 verified
raw
history blame
1.92 kB
import gradio as gr
import requests
import json
import os
# 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/2717/chat/completions"
API_TOKEN = os.environ["DATASAUR_API_KEY"]
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": 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.")
return content
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}"
with gr.Blocks() as demo:
gr.Markdown("# Memo Improvement Workflow")
with gr.Row():
text_area = gr.Textbox(label="Your Text", lines=20, scale=4)
with gr.Column(scale=1):
magic_button = gr.Button("Magic Button")
magic_button.click(
fn=magic_function,
inputs=text_area,
outputs=text_area
)
if __name__ == "__main__":
demo.launch()