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

Update app.py

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