Nick088 commited on
Commit
177be06
·
verified ·
1 Parent(s): 5b459ff

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import groq
2
+ import gradio as gr
3
+ import re
4
+ import json
5
+ import os
6
+
7
+
8
+ # Setup Groq
9
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
10
+ model = "llama-3.3-70b-versatile"
11
+
12
+ def handle_groq_error(e, model_name):
13
+ error_data = e.args[0]
14
+
15
+ if isinstance(error_data, str):
16
+ # Use regex to extract the JSON part of the string
17
+ json_match = re.search(r'(\{.*\})', error_data)
18
+ if json_match:
19
+ json_str = json_match.group(1)
20
+ # Ensure the JSON string is well-formed
21
+ json_str = json_str.replace("'", '"') # Replace single quotes with double quotes
22
+ error_data = json.loads(json_str)
23
+
24
+ if isinstance(e, groq.RateLimitError):
25
+ if isinstance(error_data, dict) and 'error' in error_data and 'message' in error_data['error']:
26
+ error_message = error_data['error']['message']
27
+ raise gr.Error(error_message)
28
+ else:
29
+ raise gr.Error(f"Error during Groq API call: {e}")
30
+
31
+
32
+
33
+ def calculate_and_roast(expression):
34
+ try:
35
+ # Basic calculator functionality (limited for safety)
36
+ allowed_chars = set("0123456789+-*/(). ")
37
+ if not all(char in allowed_chars for char in expression):
38
+ return "Invalid input: Only numbers and basic operators (+, -, *, /) are allowed.", None
39
+
40
+ result = eval(expression)
41
+
42
+ # Groq API call
43
+ try:
44
+ prompt = f"Roast me for calculating something as simple as '{expression}'. Make it funny."
45
+ response = client.request(model, {"prompt": prompt})
46
+ roast = response["text"][0]
47
+ return result, roast
48
+
49
+ except groq.GroqApiException as e:
50
+ handle_groq_error(e, model)
51
+
52
+ except (ValueError, TypeError, SyntaxError, ZeroDivisionError) as e:
53
+ return f"Calculation error: {e}", None
54
+
55
+
56
+
57
+ with gr.Blocks() as interface:
58
+ input_expression = gr.Textbox(label="Enter an expression")
59
+ calculate_button = gr.Button("Calculate and Roast")
60
+ output_result = gr.Textbox(label="Result")
61
+ output_roast = gr.Textbox(label="Roast")
62
+
63
+ calculate_button.click(
64
+ fn=calculate_and_roast,
65
+ inputs=input_expression,
66
+ outputs=[output_result, output_roast],
67
+ )
68
+
69
+
70
+ interface.launch(share=True)