Spaces:
Sleeping
Sleeping
Yongdong Wang
commited on
Commit
·
a1f2008
1
Parent(s):
9d3765e
Add JSON processing support for Python dict format in model responses
Browse files- Added JsonProcessor module to handle Python dictionary to JSON conversion
- Enhanced response processing to automatically format single quotes and
None values
- Updated requirements.txt to include loguru dependency
- Model responses now support both Python dict and JSON formats seamlessly
- app.py +31 -0
- json_processor.py +46 -0
- requirements.txt +1 -0
app.py
CHANGED
@@ -2,6 +2,8 @@ import gradio as gr
|
|
2 |
import spaces # Import spaces module for ZeroGPU
|
3 |
from huggingface_hub import login
|
4 |
import os
|
|
|
|
|
5 |
|
6 |
# 1) Read Secrets
|
7 |
hf_token = os.getenv("HUGGINGFACE_TOKEN")
|
@@ -93,6 +95,32 @@ def load_model_on_gpu():
|
|
93 |
print(f"❌ Model loading failed: {load_error}")
|
94 |
raise load_error
|
95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
@spaces.GPU(duration=60) # GPU inference
|
97 |
def generate_response_gpu(prompt, max_tokens=512):
|
98 |
"""Generate response - executed on GPU"""
|
@@ -148,6 +176,9 @@ def generate_response_gpu(prompt, max_tokens=512):
|
|
148 |
elif len(response) > len(formatted_prompt):
|
149 |
response = response[len(formatted_prompt):].strip()
|
150 |
|
|
|
|
|
|
|
151 |
return response if response else "❌ No response generated. Please try again with a different prompt."
|
152 |
|
153 |
except Exception as generation_error:
|
|
|
2 |
import spaces # Import spaces module for ZeroGPU
|
3 |
from huggingface_hub import login
|
4 |
import os
|
5 |
+
from json_processor import JsonProcessor
|
6 |
+
import json
|
7 |
|
8 |
# 1) Read Secrets
|
9 |
hf_token = os.getenv("HUGGINGFACE_TOKEN")
|
|
|
95 |
print(f"❌ Model loading failed: {load_error}")
|
96 |
raise load_error
|
97 |
|
98 |
+
def process_json_in_response(response):
|
99 |
+
"""Process and format JSON content in the response"""
|
100 |
+
try:
|
101 |
+
# Check if response contains JSON-like content
|
102 |
+
if '{' in response and '}' in response:
|
103 |
+
processor = JsonProcessor()
|
104 |
+
|
105 |
+
# Try to process the response for JSON content
|
106 |
+
processed_json = processor.process_response(response)
|
107 |
+
|
108 |
+
if processed_json:
|
109 |
+
# Format the JSON nicely
|
110 |
+
formatted_json = json.dumps(processed_json, indent=2, ensure_ascii=False)
|
111 |
+
# Replace the JSON part in the response
|
112 |
+
import re
|
113 |
+
json_pattern = r'\{.*\}'
|
114 |
+
match = re.search(json_pattern, response, re.DOTALL)
|
115 |
+
if match:
|
116 |
+
# Replace the matched JSON with the formatted version
|
117 |
+
response = response.replace(match.group(), formatted_json)
|
118 |
+
|
119 |
+
return response
|
120 |
+
except Exception:
|
121 |
+
# If processing fails, return original response
|
122 |
+
return response
|
123 |
+
|
124 |
@spaces.GPU(duration=60) # GPU inference
|
125 |
def generate_response_gpu(prompt, max_tokens=512):
|
126 |
"""Generate response - executed on GPU"""
|
|
|
176 |
elif len(response) > len(formatted_prompt):
|
177 |
response = response[len(formatted_prompt):].strip()
|
178 |
|
179 |
+
# Process JSON if present in response
|
180 |
+
response = process_json_in_response(response)
|
181 |
+
|
182 |
return response if response else "❌ No response generated. Please try again with a different prompt."
|
183 |
|
184 |
except Exception as generation_error:
|
json_processor.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import re
|
3 |
+
import ast
|
4 |
+
from loguru import logger
|
5 |
+
|
6 |
+
class JsonProcessor:
|
7 |
+
def process_response(self, response):
|
8 |
+
try:
|
9 |
+
# Search for JSON string in the response
|
10 |
+
json_str_match = re.search(r'\{.*\}', response, re.DOTALL)
|
11 |
+
if json_str_match:
|
12 |
+
# Get the matched JSON string
|
13 |
+
json_str = json_str_match.group()
|
14 |
+
logger.debug(f"Full JSON string: {json_str}")
|
15 |
+
|
16 |
+
# Try to parse as Python literal first, then convert to JSON
|
17 |
+
try:
|
18 |
+
# First try to evaluate as Python literal
|
19 |
+
python_obj = ast.literal_eval(json_str)
|
20 |
+
# Convert to proper JSON
|
21 |
+
response_json = json.loads(json.dumps(python_obj))
|
22 |
+
except (ValueError, SyntaxError):
|
23 |
+
# Fall back to string replacement method
|
24 |
+
# Replace escape characters and remove trailing commas
|
25 |
+
json_str = json_str.replace("\\", "")
|
26 |
+
json_str = json_str.replace(r'\\_', '_')
|
27 |
+
json_str = re.sub(r',\s*}', '}', json_str)
|
28 |
+
json_str = re.sub(r',\s*\]', ']', json_str)
|
29 |
+
|
30 |
+
# Convert Python format to JSON format
|
31 |
+
json_str = json_str.replace("'", '"') # Single quotes to double quotes
|
32 |
+
json_str = json_str.replace('None', 'null') # Python None to JSON null
|
33 |
+
|
34 |
+
# Parse the JSON string
|
35 |
+
response_json = json.loads(json_str)
|
36 |
+
return response_json
|
37 |
+
else:
|
38 |
+
logger.error("No JSON string match found in response.")
|
39 |
+
return None
|
40 |
+
|
41 |
+
except json.JSONDecodeError as e:
|
42 |
+
logger.error(f"JSONDecodeError: {e}")
|
43 |
+
except Exception as e:
|
44 |
+
logger.error(f"Unexpected error: {e}")
|
45 |
+
|
46 |
+
return None
|
requirements.txt
CHANGED
@@ -9,3 +9,4 @@ scipy
|
|
9 |
sentencepiece
|
10 |
protobuf
|
11 |
spaces
|
|
|
|
9 |
sentencepiece
|
10 |
protobuf
|
11 |
spaces
|
12 |
+
loguru
|