rawanessam commited on
Commit
14fd623
·
verified ·
1 Parent(s): 6ccee3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -41
app.py CHANGED
@@ -1,59 +1,82 @@
1
  import gradio as gr
2
  import json
 
3
 
4
- def extract_bq_codes_from_json(input_data):
5
- # Debug: Print raw input
6
- print("Raw input received:", type(input_data), input_data)
7
-
8
- # Handle all possible input formats
9
- if isinstance(input_data, dict):
10
- if "data" in input_data: # Gradio API format
11
- try:
12
- if isinstance(input_data["data"][0], str):
13
- data = json.loads(input_data["data"][0])
14
- else:
15
- data = input_data["data"][0]
16
- except Exception as e:
17
- print("API format parse error:", e)
18
- return {"error": f"Invalid API format: {str(e)}"}
19
- else: # Raw JSON format
20
- data = input_data
21
- elif isinstance(input_data, str): # Direct text input
22
- try:
23
- data = json.loads(input_data)
24
- except Exception as e:
25
- print("String parse error:", e)
26
- return {"error": f"Invalid JSON string: {str(e)}"}
27
- else:
28
- return {"error": "Input must be JSON string or object"}
29
-
30
- # Extraction logic with defensive programming
31
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  codes = set()
33
  for project in data.get("projecttemplates", []):
 
 
 
34
  for detail in project.get("projecttemplatedetails", []):
35
- if isinstance(detail, dict):
36
- bqcode = detail.get("bqcodelibrary", {}).get("bqcode")
37
- if bqcode:
38
- codes.add(bqcode)
39
- return {"success": True, "codes": list(codes)}
 
 
 
 
 
 
 
 
 
 
 
40
  except Exception as e:
41
- return {"error": f"Processing error: {str(e)}", "received_data": data}
42
 
43
- # Create interface with explicit examples
44
  examples = [
45
- {'projecttemplates': [{'projecttemplatedetails': [{'bqcodelibrary': {'bqcode': 'BQ123'}}]}]},
46
- '{"projecttemplates":[{"projecttemplatedetails":[{"bqcodelibrary":{"bqcode":"BQ456"}}]}]'
47
  ]
48
 
49
  iface = gr.Interface(
50
  fn=extract_bq_codes_from_json,
51
- inputs=gr.Textbox(lines=10, placeholder="Paste JSON here...", label="JSON Input"),
52
- outputs=gr.JSON(label="Results"),
53
  examples=examples,
54
- title="BQ Code Extractor",
55
- description="Extracts BQ codes from JSON. Accepts both raw JSON objects and strings."
 
 
 
 
56
  )
57
 
58
  if __name__ == "__main__":
59
- iface.launch(debug=True)
 
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
41
+
42
  for detail in project.get("projecttemplatedetails", []):
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)