rawanessam commited on
Commit
6e2eb5e
·
verified ·
1 Parent(s): bf5e128

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -27
app.py CHANGED
@@ -1,40 +1,70 @@
1
  import gradio as gr
2
  import json
3
- from typing import Union
4
 
5
- def extract_bq_codes_from_json(input_data: Union[str, dict]):
6
  """
7
  Robust JSON processor that handles:
8
  - Direct API calls (raw JSON)
9
  - Gradio API format ({"data": [...]})
10
  - String input from UI
 
 
 
 
 
 
 
 
11
  """
12
  try:
13
  # Debugging: Log raw input
14
- print(f"\n--- Received input ---\nType: {type(input_data)}\nContent: {input_data}\n")
15
 
16
  # Phase 1: Parse input
17
  if isinstance(input_data, dict):
18
  if "data" in input_data: # Gradio API format
19
  if not input_data["data"]:
20
- return {"error": "Empty data array"}
21
  content = input_data["data"][0]
22
  data = json.loads(content) if isinstance(content, str) else content
23
  else: # Raw JSON format
24
  data = input_data
25
  elif isinstance(input_data, str):
26
- data = json.loads(input_data)
 
 
 
 
 
 
 
27
  else:
28
- return {"error": f"Unsupported input type: {type(input_data)}"}
 
 
 
 
29
 
30
- # Debugging: Log parsed data
31
- print(f"--- Parsed data ---\n{data}\n")
32
-
33
- # Phase 2: Process data
34
  if not isinstance(data, dict):
35
- return {"error": f"Expected dictionary, got {type(data)}"}
 
 
 
 
 
 
 
 
 
 
 
36
 
 
37
  codes = set()
 
 
38
  for project in data.get("projecttemplates", []):
39
  if not isinstance(project, dict):
40
  continue
@@ -43,40 +73,84 @@ def extract_bq_codes_from_json(input_data: Union[str, dict]):
43
  if not isinstance(detail, dict):
44
  continue
45
 
46
- bqcode = detail.get("bqcodelibrary", {}).get("bqcode")
47
- if bqcode and isinstance(bqcode, str):
48
- codes.add(bqcode)
 
 
 
49
 
50
  return {
51
  "success": True,
52
  "codes": sorted(list(codes)),
53
  "input_type": str(type(input_data)),
54
- "processed_at": gr.utils.get_current_time()
55
  }
56
 
57
- except json.JSONDecodeError as e:
58
- return {"error": f"Invalid JSON: {str(e)}", "input": str(input_data)}
59
  except Exception as e:
60
- return {"error": f"Unexpected error: {str(e)}", "type": str(type(e))}
 
 
 
 
 
61
 
62
- # Example data for the interface
63
  examples = [
64
- json.dumps({"projecttemplates": [{"projecttemplatedetails": [{"bqcodelibrary": {"bqcode": "BQ001"}}]}]}),
65
- {"projecttemplates": [{"projecttemplatedetails": [{"bqcodelibrary": {"bqcode": "BQ002"}}]}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  ]
67
 
68
  iface = gr.Interface(
69
- fn=extract_bq_codes_from_json,
70
- inputs=gr.Textbox(lines=10, label="JSON Input", placeholder='Paste JSON here or use examples below...'),
 
 
 
 
 
71
  outputs=gr.JSON(label="Extraction Results"),
72
  examples=examples,
73
- title="BQ Code Extractor (Robust Version)",
74
- description="""Extracts BQ codes from JSON structures. Accepts:
 
75
  - Raw JSON strings
76
  - JSON objects
77
  - Gradio API format""",
78
- allow_flagging="never"
 
79
  )
80
 
 
81
  if __name__ == "__main__":
82
- iface.launch(debug=True, show_error=True)
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import json
3
+ from typing import Union, List, Dict, Any
4
 
5
+ def extract_bq_codes(input_data: Union[str, Dict]) -> Dict[str, Any]:
6
  """
7
  Robust JSON processor that handles:
8
  - Direct API calls (raw JSON)
9
  - Gradio API format ({"data": [...]})
10
  - String input from UI
11
+
12
+ Returns:
13
+ {
14
+ "success": bool,
15
+ "codes": List[str],
16
+ "error": Optional[str],
17
+ "input_type": str
18
+ }
19
  """
20
  try:
21
  # Debugging: Log raw input
22
+ print(f"\n--- Received input ---\nType: {type(input_data)}\nContent: {input_data[:200]}...\n")
23
 
24
  # Phase 1: Parse input
25
  if isinstance(input_data, dict):
26
  if "data" in input_data: # Gradio API format
27
  if not input_data["data"]:
28
+ return {"success": False, "error": "Empty data array"}
29
  content = input_data["data"][0]
30
  data = json.loads(content) if isinstance(content, str) else content
31
  else: # Raw JSON format
32
  data = input_data
33
  elif isinstance(input_data, str):
34
+ try:
35
+ data = json.loads(input_data)
36
+ except json.JSONDecodeError as e:
37
+ return {
38
+ "success": False,
39
+ "error": f"Invalid JSON string: {str(e)}",
40
+ "input_type": str(type(input_data))
41
+ }
42
  else:
43
+ return {
44
+ "success": False,
45
+ "error": f"Unsupported input type: {type(input_data)}",
46
+ "input_type": str(type(input_data))
47
+ }
48
 
49
+ # Phase 2: Validate data structure
 
 
 
50
  if not isinstance(data, dict):
51
+ return {
52
+ "success": False,
53
+ "error": f"Expected dictionary, got {type(data)}",
54
+ "input_type": str(type(input_data))
55
+ }
56
+
57
+ if "projecttemplates" not in data:
58
+ return {
59
+ "success": False,
60
+ "error": "Missing 'projecttemplates' in JSON",
61
+ "input_type": str(type(input_data))
62
+ }
63
 
64
+ # Phase 3: Process data
65
  codes = set()
66
+
67
+ # Safely navigate through the complex nested structure
68
  for project in data.get("projecttemplates", []):
69
  if not isinstance(project, dict):
70
  continue
 
73
  if not isinstance(detail, dict):
74
  continue
75
 
76
+ # Handle potential None values in bqcodelibrary
77
+ bqcode_lib = detail.get("bqcodelibrary")
78
+ if bqcode_lib and isinstance(bqcode_lib, dict):
79
+ bqcode = bqcode_lib.get("bqcode")
80
+ if bqcode and isinstance(bqcode, str):
81
+ codes.add(bqcode)
82
 
83
  return {
84
  "success": True,
85
  "codes": sorted(list(codes)),
86
  "input_type": str(type(input_data)),
87
+ "count": len(codes)
88
  }
89
 
 
 
90
  except Exception as e:
91
+ return {
92
+ "success": False,
93
+ "error": f"Unexpected error: {str(e)}",
94
+ "type": str(type(e)),
95
+ "input_type": str(type(input_data)) if 'input_data' in locals() else "unknown"
96
+ }
97
 
98
+ # Create interface with improved examples
99
  examples = [
100
+ json.dumps({
101
+ "projecttemplates": [
102
+ {
103
+ "projecttemplatedetails": [
104
+ {
105
+ "bqcodelibrary": {
106
+ "bqcode": "F10.01.01.01.00_block"
107
+ }
108
+ }
109
+ ]
110
+ }
111
+ ]
112
+ }),
113
+ {
114
+ "projecttemplates": [
115
+ {
116
+ "projecttemplatedetails": [
117
+ {
118
+ "bqcodelibrary": {
119
+ "bqcode": "L20.01.00.01.00_doors"
120
+ }
121
+ }
122
+ ]
123
+ }
124
+ ]
125
+ }
126
  ]
127
 
128
  iface = gr.Interface(
129
+ fn=extract_bq_codes,
130
+ inputs=gr.Textbox(
131
+ lines=15,
132
+ label="JSON Input",
133
+ placeholder='Paste your complex JSON here...',
134
+ max_lines=25
135
+ ),
136
  outputs=gr.JSON(label="Extraction Results"),
137
  examples=examples,
138
+ title="BQ Code Extractor (Enterprise Version)",
139
+ description="""Safely extracts BQ codes from complex construction project JSON structures.
140
+ Accepts:
141
  - Raw JSON strings
142
  - JSON objects
143
  - Gradio API format""",
144
+ allow_flagging="never",
145
+ theme="default"
146
  )
147
 
148
+ # Launch with production-ready settings
149
  if __name__ == "__main__":
150
+ iface.launch(
151
+ server_name="0.0.0.0",
152
+ server_port=7860,
153
+ debug=True,
154
+ show_error=True,
155
+ enable_queue=True
156
+ )