Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,51 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import json
|
4 |
|
5 |
+
# WARNING: It is not recommended to hardcode sensitive data like API tokens in code.
|
6 |
+
# Consider using environment variables or other secure methods for production applications.
|
7 |
+
API_URL = "https://deployment.datasaur.ai/api/deployment/8/2717/chat/completions"
|
8 |
+
API_TOKEN = "ds-bb8f69148d3e4ae3aed327af3da5eb4a"
|
9 |
|
10 |
+
def magic_function(input_text):
|
11 |
+
"""
|
12 |
+
Sends text to the Datasaur deployment API and returns the processed text.
|
13 |
+
"""
|
14 |
+
headers = {
|
15 |
+
"Content-Type": "application/json",
|
16 |
+
"Authorization": f"Bearer {API_TOKEN}",
|
17 |
+
}
|
18 |
+
data = {
|
19 |
+
"messages": [{"role": "user", "content": input_text}]
|
20 |
+
}
|
21 |
+
|
22 |
+
try:
|
23 |
+
response = requests.post(API_URL, headers=headers, json=data)
|
24 |
+
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
|
25 |
+
|
26 |
+
response_json = response.json()
|
27 |
+
|
28 |
+
# Extract content from a standard chat completion response structure.
|
29 |
+
# This may need adjustment if the API has a different format.
|
30 |
+
content = response_json.get("choices", [{}])[0].get("message", {}).get("content", "Error: Could not parse response.")
|
31 |
+
return content
|
32 |
+
|
33 |
+
except requests.exceptions.RequestException as e:
|
34 |
+
return f"API Request Error: {e}"
|
35 |
+
except (ValueError, KeyError, IndexError):
|
36 |
+
# Handle cases where response is not valid JSON or structure is unexpected
|
37 |
+
return f"Error processing API response: {response.text}"
|
38 |
+
|
39 |
+
|
40 |
+
with gr.Blocks() as demo:
|
41 |
+
text_area = gr.Textbox(label="Your Text", lines=20)
|
42 |
+
magic_button = gr.Button("Magic Button")
|
43 |
+
|
44 |
+
magic_button.click(
|
45 |
+
fn=magic_function,
|
46 |
+
inputs=text_area,
|
47 |
+
outputs=text_area
|
48 |
+
)
|
49 |
+
|
50 |
+
if __name__ == "__main__":
|
51 |
+
demo.launch()
|