Reza-galaxy21 commited on
Commit
eb55547
·
verified ·
1 Parent(s): b48a43f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -70
app.py CHANGED
@@ -1,107 +1,91 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import os
4
  import json
 
5
 
6
- JSON_PATH = "/tmp/material_db.json"
 
 
 
 
7
 
8
- def parse_excel(file):
9
  try:
10
  df = pd.read_excel(file.name, header=2)
11
  except Exception as e:
12
- return None, None, f"❌ خطا در خواندن فایل اکسل: {str(e)}"
13
-
14
- column_mapping = {
15
- "code": ["کد", "کد فهرست بها"],
16
- "description": ["عنوان", "شرح کالا", "نام کالا"],
17
- "quantity": ["تعداد", "تعداد مورد نیاز"],
18
- "unit": ["واحد", "واحد شمارش", "نوع واحد"]
19
- }
20
 
21
- resolved = {}
22
- for key, options in column_mapping.items():
23
- found = next((col for col in options if col in df.columns), None)
24
- if not found:
25
- return None, None, f"❌ ستون «{key}» در فایل پیدا نشد."
26
- resolved[key] = found
27
 
28
- materials = []
29
  constraints = []
 
 
30
  for _, row in df.iterrows():
31
  try:
32
- qty = float(row[resolved["quantity"]])
33
- if pd.isna(qty) or qty <= 0:
34
- continue
35
  except:
36
  continue
37
 
38
- material = {
39
- "code": str(row[resolved["code"]]).strip(),
40
- "description": str(row[resolved["description"]]).strip(),
 
 
 
 
41
  "quantity": qty,
42
- "unit": str(row[resolved["unit"]]).strip()
43
- }
44
- materials.append(material)
45
 
46
- constraints.append(f"{material['description']} ({material['quantity']} {material['unit']})")
 
 
 
47
 
 
48
  try:
49
- if os.path.exists(JSON_PATH):
50
- with open(JSON_PATH, "r", encoding="utf-8") as f:
51
- existing = json.load(f)
52
  else:
53
- existing = []
54
 
55
- new_materials = [m for m in materials if m not in existing]
56
- existing.extend(new_materials)
57
 
58
- with open(JSON_PATH, "w", encoding="utf-8") as f:
59
- json.dump(existing, f, indent=2, ensure_ascii=False)
60
 
61
  except Exception as e:
62
- return None, None, f"❌ خطا در ذخیره فایل JSON: {str(e)}"
63
-
64
- return constraints, len(new_materials), f"✅ {len(new_materials)} مورد جدید با موفقیت ثبت شدند."
65
 
 
66
 
67
- def get_json_file():
68
- if os.path.exists(JSON_PATH):
69
- return JSON_PATH
70
- else:
71
- return None
72
 
73
-
74
- with gr.Blocks(title="مدیریت مواد پروژه") as demo:
75
- gr.Markdown("""
76
- # 🛠️ سامانه ثبت اقلام پروژه
77
-
78
- در این ابزار می‌توانید فایل اکسل برآورد مصالح پروژه را بارگذاری کرده،
79
- اقلام را استخراج و ثبت نمایید. همچنین امکان دریافت خروجی JSON فراهم است.
80
- """)
81
 
82
  with gr.Row():
83
- file_input = gr.File(label="📂 انتخاب فایل اکسل")
84
- upload_btn = gr.Button("📤 ثبت اقلام")
85
-
86
- status_output = gr.Textbox(label="وضعیت", lines=2)
87
- constraints_output = gr.Textbox(label="🔍 اقلام استخراج‌شده", lines=10)
88
 
89
- download_btn = gr.Button("📥 دریافت فایل JSON")
90
- json_file_output = gr.File(label="دانلود فایل", visible=False)
 
91
 
92
- def handle_upload(file):
93
- if file is None:
94
- return "", "", "⚠️ لطفاً یک فایل اکسل انتخاب کنید."
95
- constraints, count, msg = parse_excel(file)
96
- joined = "\n".join(constraints) if constraints else ""
97
- return msg, joined
98
 
99
- def handle_download():
100
- path = get_json_file()
101
- return path if path else None
102
 
103
- upload_btn.click(handle_upload, inputs=[file_input], outputs=[status_output, constraints_output])
104
- download_btn.click(handle_download, outputs=[json_file_output])
105
 
106
  if __name__ == "__main__":
107
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
 
3
  import json
4
+ import os
5
 
6
+ DB_PATH = "/tmp/material_db.json"
7
+
8
+ def extract_materials(file, description):
9
+ if file is None or description.strip() == "":
10
+ return "❌ لطفاً فایل اکسل و توضیح پروژه را وارد کنید.", "", None
11
 
 
12
  try:
13
  df = pd.read_excel(file.name, header=2)
14
  except Exception as e:
15
+ return f"❌ خطا در خواندن فایل: {e}", "", None
 
 
 
 
 
 
 
16
 
17
+ required_cols = ["شرح کالا", "تعداد", "واحد"]
18
+ for col in required_cols:
19
+ if col not in df.columns:
20
+ return f"❌ ستون '{col}' در فایل یافت نشد.", "", None
 
 
21
 
 
22
  constraints = []
23
+ materials = []
24
+
25
  for _, row in df.iterrows():
26
  try:
27
+ desc = str(row["شرح کالا"]).strip()
28
+ qty = float(row["تعداد"])
29
+ unit = str(row["واحد"]).strip()
30
  except:
31
  continue
32
 
33
+ if qty <= 0 or desc == "":
34
+ continue
35
+
36
+ constraint = f"{desc} ({qty} {unit})"
37
+ constraints.append(constraint)
38
+ materials.append({
39
+ "description": desc,
40
  "quantity": qty,
41
+ "unit": unit
42
+ })
 
43
 
44
+ record = {
45
+ "project_description": description.strip(),
46
+ "items": materials
47
+ }
48
 
49
+ # Save to JSON file
50
  try:
51
+ if os.path.exists(DB_PATH):
52
+ with open(DB_PATH, "r", encoding="utf-8") as f:
53
+ data = json.load(f)
54
  else:
55
+ data = []
56
 
57
+ data.append(record)
 
58
 
59
+ with open(DB_PATH, "w", encoding="utf-8") as f:
60
+ json.dump(data, f, ensure_ascii=False, indent=2)
61
 
62
  except Exception as e:
63
+ return f"❌ خطا در ذخیره فایل JSON: {e}", "", None
 
 
64
 
65
+ return f"✅ {len(materials)} قلم با موفقیت ثبت شد.", "\n".join(constraints), DB_PATH
66
 
67
+ def download_json():
68
+ return DB_PATH if os.path.exists(DB_PATH) else None
 
 
 
69
 
70
+ with gr.Blocks(title="ثبت اقلام و ساخت کتابخانه قیود") as demo:
71
+ gr.Markdown("## 📁 ثبت اقلام پروژه و ساخت کتابخانه قیود")
 
 
 
 
 
 
72
 
73
  with gr.Row():
74
+ file_input = gr.File(label="📂 بارگذاری فایل اکسل")
75
+ description_input = gr.Textbox(label="📝 توصیف پروژه", placeholder="مثلاً: پروژه خط انتقال 63 کیلوولت تبریز")
 
 
 
76
 
77
+ upload_btn = gr.Button("📤 ثبت اقلام")
78
+ status_output = gr.Textbox(label="📌 وضعیت", lines=2)
79
+ constraints_output = gr.Textbox(label="🧾 قیود استخراج‌شده", lines=10)
80
 
81
+ download_btn = gr.Button("📥 دانلود فایل JSON")
82
+ json_file_output = gr.File(label="فایل خروجی", visible=True)
 
 
 
 
83
 
84
+ upload_btn.click(fn=extract_materials,
85
+ inputs=[file_input, description_input],
86
+ outputs=[status_output, constraints_output, json_file_output])
87
 
88
+ download_btn.click(fn=download_json, outputs=json_file_output)
 
89
 
90
  if __name__ == "__main__":
91
  demo.launch()