MuhammadSajid commited on
Commit
d3e6e51
Β·
verified Β·
1 Parent(s): 0dad244

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -58
app.py CHANGED
@@ -1,14 +1,12 @@
1
- import gradio as gr
2
  import os
 
3
  import ezdxf
 
 
4
  import groq
5
- from ezdxf.entities import Insert, Line, Text, LWPolyline
6
-
7
- # Initialize Groq client
8
- client = groq.Client(api_key=os.getenv("GROQ_API_KEY"))
9
 
10
- # Parse the DXF file and extract basic entities
11
- def analyze_autocad_project(file_path):
12
  try:
13
  doc = ezdxf.readfile(file_path)
14
  msp = doc.modelspace()
@@ -17,29 +15,35 @@ def analyze_autocad_project(file_path):
17
  connections = []
18
 
19
  for entity in msp:
20
- if isinstance(entity, Insert):
21
- name = entity.dxf.name
22
- location = entity.dxf.insert
23
- components.append({"type": "BLOCK", "name": name, "location": (location.x, location.y)})
24
- elif isinstance(entity, Line):
25
- start = (entity.dxf.start.x, entity.dxf.start.y)
26
- end = (entity.dxf.end.x, entity.dxf.end.y)
27
- connections.append({"type": "LINE", "start": start, "end": end})
28
- elif isinstance(entity, LWPolyline):
29
- points = entity.get_points("xy")
30
- connections.append({"type": "POLYLINE", "points": points})
31
- elif isinstance(entity, Text):
32
- components.append({"type": "TEXT", "content": entity.dxf.text, "location": (entity.dxf.insert.x, entity.dxf.insert.y)})
33
-
34
- summary = f"πŸ” Found {len(components)} components and {len(connections)} connections."
35
- return summary, {"components": components, "connections": connections}
 
 
 
 
36
  except Exception as e:
37
- return f"❌ Error: {str(e)}", None
 
 
38
 
39
- # RAG + Groq: Ask questions about specific components
40
  def ask_groq_question(context_dict, query):
41
  try:
42
- # Provide summarized context to Groq
 
43
  component_text = "\n".join(
44
  [f"{comp['type']} - {comp.get('name', comp.get('content', ''))} at {comp['location']}" for comp in context_dict["components"]]
45
  )
@@ -56,42 +60,45 @@ def ask_groq_question(context_dict, query):
56
  except Exception as e:
57
  return f"Groq Error: {str(e)}"
58
 
59
- # Global store for RAG context
60
- rag_context = {}
61
-
62
- # Gradio Interface
63
- def upload_and_analyze(file):
64
- summary, context = analyze_autocad_project(file.name)
65
- if context:
66
- global rag_context
67
- rag_context = context
68
- return summary
69
-
70
- def query_component(user_query):
71
- if not rag_context:
72
- return "⚠️ Please upload and analyze a DXF file first."
73
- return ask_groq_question(rag_context, user_query)
74
-
75
- with gr.Blocks() as app:
76
- gr.Markdown("# πŸ”Œ AutoCAD Electrical Project Analyzer with Groq RAG")
77
- gr.Markdown("""
78
- Upload your AutoCAD DXF file to analyze the electrical project layout. Ask questions about specific components, connections, or trace paths.
79
- """)
 
 
 
 
80
 
81
  with gr.Row():
82
- file_input = gr.File(label="πŸ“ Upload AutoCAD DXF Project")
83
- upload_btn = gr.Button("πŸ“Š Analyze Project")
84
-
85
- analysis_result = gr.Textbox(label="πŸ“ Analysis Summary")
86
 
87
- upload_btn.click(fn=upload_and_analyze, inputs=file_input, outputs=analysis_result)
 
88
 
89
- gr.Markdown("### πŸ’¬ Ask about Component Back-tracing or Details")
90
- user_query = gr.Textbox(label="πŸ” Enter your question (e.g., trace component R1)")
91
- answer_box = gr.Textbox(label="🧠 Groq RAG Answer")
92
 
93
- ask_btn = gr.Button("🧠 Ask Groq")
94
- ask_btn.click(fn=query_component, inputs=user_query, outputs=answer_box)
95
 
96
  if __name__ == "__main__":
97
- app.launch()
 
 
1
  import os
2
+ import gradio as gr
3
  import ezdxf
4
+ import tempfile
5
+ import json
6
  import groq
 
 
 
 
7
 
8
+ # Function to parse the DXF and extract simple components and connections
9
+ def analyze_dxf(file_path):
10
  try:
11
  doc = ezdxf.readfile(file_path)
12
  msp = doc.modelspace()
 
15
  connections = []
16
 
17
  for entity in msp:
18
+ if entity.dxftype() == "INSERT":
19
+ components.append({
20
+ "type": "BlockReference",
21
+ "name": entity.dxf.name,
22
+ "location": f"({entity.dxf.insert[0]}, {entity.dxf.insert[1]})"
23
+ })
24
+ elif entity.dxftype() == "TEXT":
25
+ components.append({
26
+ "type": "Text",
27
+ "content": entity.dxf.text,
28
+ "location": f"({entity.dxf.insert[0]}, {entity.dxf.insert[1]})"
29
+ })
30
+ elif entity.dxftype() == "LINE":
31
+ connections.append({
32
+ "type": "Line",
33
+ "start": f"({entity.dxf.start[0]}, {entity.dxf.start[1]})",
34
+ "end": f"({entity.dxf.end[0]}, {entity.dxf.end[1]})"
35
+ })
36
+
37
+ return components, connections
38
  except Exception as e:
39
+ return [], []
40
+
41
+ # Function to ask Groq to analyze components
42
 
 
43
  def ask_groq_question(context_dict, query):
44
  try:
45
+ client = groq.Client(api_key=os.getenv("GROQ_API_KEY"))
46
+
47
  component_text = "\n".join(
48
  [f"{comp['type']} - {comp.get('name', comp.get('content', ''))} at {comp['location']}" for comp in context_dict["components"]]
49
  )
 
60
  except Exception as e:
61
  return f"Groq Error: {str(e)}"
62
 
63
+ # Gradio interface
64
+ def process_file(file):
65
+ if file is None:
66
+ return "⚠️ Please upload a valid AutoCAD DXF file."
67
+ components, connections = analyze_dxf(file.name)
68
+ context = {
69
+ "components": components,
70
+ "connections": connections
71
+ }
72
+ # Store context in a temp file to retrieve later
73
+ temp_path = os.path.join(tempfile.gettempdir(), "context.json")
74
+ with open(temp_path, "w") as f:
75
+ json.dump(context, f)
76
+ return "βœ… File processed and understood. Now you can ask questions."
77
+
78
+ def query_groq(user_query):
79
+ temp_path = os.path.join(tempfile.gettempdir(), "context.json")
80
+ if not os.path.exists(temp_path):
81
+ return "⚠️ No DXF context available. Please upload a file first."
82
+ with open(temp_path, "r") as f:
83
+ context = json.load(f)
84
+ return ask_groq_question(context, user_query)
85
+
86
+ with gr.Blocks() as demo:
87
+ gr.Markdown("# 🧠 RAG-based AutoCAD Analyzer with Groq")
88
 
89
  with gr.Row():
90
+ file_input = gr.File(label="πŸ“ Upload AutoCAD DXF File", file_types=['.dxf'])
91
+ file_output = gr.Textbox(label="Status", interactive=False)
 
 
92
 
93
+ process_btn = gr.Button("πŸ” Analyze DXF")
94
+ process_btn.click(process_file, inputs=[file_input], outputs=[file_output])
95
 
96
+ with gr.Row():
97
+ user_query = gr.Textbox(label="πŸ”Ž Ask a Question about the Circuit")
98
+ response = gr.Textbox(label="πŸ’¬ Groq Answer")
99
 
100
+ ask_btn = gr.Button("πŸ€– Ask Groq")
101
+ ask_btn.click(query_groq, inputs=[user_query], outputs=[response])
102
 
103
  if __name__ == "__main__":
104
+ demo.launch()