Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -39,7 +39,6 @@ MODELS = {
|
|
| 39 |
}
|
| 40 |
}
|
| 41 |
|
| 42 |
-
# Define all invoice extraction functions first
|
| 43 |
def get_api_key(model_choice):
|
| 44 |
"""Get the appropriate API key based on model choice"""
|
| 45 |
api_key_env = MODELS[model_choice]["api_key_env"]
|
|
@@ -49,44 +48,6 @@ def get_api_key(model_choice):
|
|
| 49 |
st.stop()
|
| 50 |
return api_key
|
| 51 |
|
| 52 |
-
def clean_json_response(text):
|
| 53 |
-
"""Improved JSON extraction from API response with better error handling"""
|
| 54 |
-
# First try to parse directly as JSON
|
| 55 |
-
try:
|
| 56 |
-
return json.loads(text)
|
| 57 |
-
except json.JSONDecodeError:
|
| 58 |
-
pass
|
| 59 |
-
|
| 60 |
-
# Try to extract JSON from markdown code blocks
|
| 61 |
-
json_match = re.search(r'```(?:json)?\n({.*?})\n```', text, re.DOTALL)
|
| 62 |
-
if json_match:
|
| 63 |
-
try:
|
| 64 |
-
return json.loads(json_match.group(1))
|
| 65 |
-
except json.JSONDecodeError:
|
| 66 |
-
pass
|
| 67 |
-
|
| 68 |
-
# Try to extract any JSON-like content
|
| 69 |
-
json_match = re.search(r'\{.*\}', text, re.DOTALL)
|
| 70 |
-
if json_match:
|
| 71 |
-
try:
|
| 72 |
-
return json.loads(json_match.group(0))
|
| 73 |
-
except json.JSONDecodeError:
|
| 74 |
-
pass
|
| 75 |
-
|
| 76 |
-
# Fallback to simple key-value parsing
|
| 77 |
-
try:
|
| 78 |
-
data = {}
|
| 79 |
-
for line in text.split('\n'):
|
| 80 |
-
if ':' in line:
|
| 81 |
-
parts = line.split(':', 1)
|
| 82 |
-
if len(parts) == 2:
|
| 83 |
-
key, val = parts
|
| 84 |
-
key = key.strip().strip('"').lower().replace(' ', '_')
|
| 85 |
-
data[key] = val.strip().strip('"')
|
| 86 |
-
return data if data else None
|
| 87 |
-
except Exception:
|
| 88 |
-
return None
|
| 89 |
-
|
| 90 |
def query_llm(model_choice, prompt):
|
| 91 |
"""Call the appropriate API based on model choice"""
|
| 92 |
config = MODELS[model_choice]
|
|
@@ -122,6 +83,14 @@ def query_llm(model_choice, prompt):
|
|
| 122 |
content = response.json()["choices"][0]["message"]["content"]
|
| 123 |
st.session_state.last_api_response = content
|
| 124 |
st.session_state.last_api_response_raw = response.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
return content
|
| 126 |
except KeyError as e:
|
| 127 |
st.error(f"KeyError in response: {e}\nFull response: {response.json()}")
|
|
@@ -131,6 +100,53 @@ def query_llm(model_choice, prompt):
|
|
| 131 |
st.error(f"🌐 Connection Failed: {str(e)}")
|
| 132 |
return None
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
def get_extraction_prompt(model_choice, text):
|
| 135 |
"""Return the appropriate prompt based on model choice"""
|
| 136 |
if model_choice == "DeepSeek v3":
|
|
|
|
| 39 |
}
|
| 40 |
}
|
| 41 |
|
|
|
|
| 42 |
def get_api_key(model_choice):
|
| 43 |
"""Get the appropriate API key based on model choice"""
|
| 44 |
api_key_env = MODELS[model_choice]["api_key_env"]
|
|
|
|
| 48 |
st.stop()
|
| 49 |
return api_key
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def query_llm(model_choice, prompt):
|
| 52 |
"""Call the appropriate API based on model choice"""
|
| 53 |
config = MODELS[model_choice]
|
|
|
|
| 83 |
content = response.json()["choices"][0]["message"]["content"]
|
| 84 |
st.session_state.last_api_response = content
|
| 85 |
st.session_state.last_api_response_raw = response.text
|
| 86 |
+
|
| 87 |
+
# Special handling for Llama 4 Mavericks incomplete responses
|
| 88 |
+
if model_choice == "Llama 4 Mavericks" and content.count('{') != content.count('}'):
|
| 89 |
+
st.warning("⚠️ Received incomplete JSON response. Trying to fix...")
|
| 90 |
+
# Try to complete the JSON by adding missing closing braces
|
| 91 |
+
missing_braces = content.count('{') - content.count('}')
|
| 92 |
+
content += '}' * missing_braces + ']' * (content.count('[') - content.count(']'))
|
| 93 |
+
|
| 94 |
return content
|
| 95 |
except KeyError as e:
|
| 96 |
st.error(f"KeyError in response: {e}\nFull response: {response.json()}")
|
|
|
|
| 100 |
st.error(f"🌐 Connection Failed: {str(e)}")
|
| 101 |
return None
|
| 102 |
|
| 103 |
+
def clean_json_response(text):
|
| 104 |
+
"""Improved JSON extraction from API response with better error handling"""
|
| 105 |
+
if not text:
|
| 106 |
+
return None
|
| 107 |
+
|
| 108 |
+
# Special handling for Llama 4 Mavericks incomplete responses
|
| 109 |
+
if 'line_items":' in text and ']' not in text.split('line_items":')[-1]:
|
| 110 |
+
# Try to complete the line items array
|
| 111 |
+
text = text.split('line_items":')[0] + 'line_items": []}'
|
| 112 |
+
|
| 113 |
+
# First try to parse directly as JSON
|
| 114 |
+
try:
|
| 115 |
+
return json.loads(text)
|
| 116 |
+
except json.JSONDecodeError as e:
|
| 117 |
+
st.warning(f"First JSON parse attempt failed: {str(e)}")
|
| 118 |
+
|
| 119 |
+
# Try to extract JSON from markdown code blocks
|
| 120 |
+
json_match = re.search(r'```(?:json)?\n({.*?})\n```', text, re.DOTALL)
|
| 121 |
+
if json_match:
|
| 122 |
+
try:
|
| 123 |
+
return json.loads(json_match.group(1))
|
| 124 |
+
except json.JSONDecodeError as e:
|
| 125 |
+
st.warning(f"Markdown JSON parse failed: {str(e)}")
|
| 126 |
+
|
| 127 |
+
# Try to extract any JSON-like content
|
| 128 |
+
json_match = re.search(r'\{.*\}', text, re.DOTALL)
|
| 129 |
+
if json_match:
|
| 130 |
+
try:
|
| 131 |
+
return json.loads(json_match.group(0))
|
| 132 |
+
except json.JSONDecodeError as e:
|
| 133 |
+
st.warning(f"Loose JSON parse failed: {str(e)}")
|
| 134 |
+
|
| 135 |
+
# Fallback to simple key-value parsing
|
| 136 |
+
try:
|
| 137 |
+
data = {}
|
| 138 |
+
for line in text.split('\n'):
|
| 139 |
+
if ':' in line:
|
| 140 |
+
parts = line.split(':', 1)
|
| 141 |
+
if len(parts) == 2:
|
| 142 |
+
key, val = parts
|
| 143 |
+
key = key.strip().strip('"').lower().replace(' ', '_')
|
| 144 |
+
data[key] = val.strip().strip('"')
|
| 145 |
+
return data if data else None
|
| 146 |
+
except Exception as e:
|
| 147 |
+
st.error(f"Final fallback parse failed: {str(e)}")
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
def get_extraction_prompt(model_choice, text):
|
| 151 |
"""Return the appropriate prompt based on model choice"""
|
| 152 |
if model_choice == "DeepSeek v3":
|