Reza-galaxy21 commited on
Commit
03a5788
·
verified ·
1 Parent(s): 2236141

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -55
app.py CHANGED
@@ -5,11 +5,14 @@ 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": ["کد", "کد فهرست بها"],
@@ -22,7 +25,7 @@ def parse_excel(file):
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 = []
@@ -51,74 +54,80 @@ def parse_excel(file):
51
  else:
52
  existing = []
53
 
54
- new_materials = [m for m in materials if m not in existing]
55
- existing.extend(new_materials)
 
 
 
56
 
57
  with open(JSON_PATH, "w", encoding="utf-8") as f:
58
  json.dump(existing, f, indent=2, ensure_ascii=False)
59
 
60
  except Exception as e:
61
- return None, None, f"❌ خطا در ذخیره فایل JSON: {str(e)}"
 
 
 
 
 
62
 
63
- return constraints, len(new_materials), f"✅ {len(new_materials)} مورد جدید با موفقیت ثبت شدند."
 
 
64
 
65
- def load_json_file(file):
66
  try:
67
- with open(file.name, "r", encoding="utf-8") as f:
68
- data = json.load(f)
69
- with open(JSON_PATH, "w", encoding="utf-8") as f_out:
70
- json.dump(data, f_out, indent=2, ensure_ascii=False)
71
- return f"✅ فایل JSON با {len(data)} مورد با موفقیت بارگذاری شد."
72
  except Exception as e:
73
- return f"❌ خطا در بارگذاری فایل JSON: {str(e)}"
74
 
75
- def read_json_descriptions():
76
  if not os.path.exists(JSON_PATH):
77
- return "ℹ️ تاکنون هیچ موردی ثبت نشده است."
 
78
  try:
79
  with open(JSON_PATH, "r", encoding="utf-8") as f:
80
- data = json.load(f)
81
- descriptions = [f"{item['description']} ({item['quantity']} {item['unit']})" for item in data]
82
- return "\n".join(descriptions)
 
 
 
 
83
  except Exception as e:
84
  return f"❌ خطا در خواندن فایل JSON: {str(e)}"
85
 
86
  with gr.Blocks(title="مدیریت مواد پروژه - نسخه 0.1.1") as demo:
87
- with gr.Tabs():
88
- with gr.TabItem("📤 بارگذاری فایل اکسل"):
89
- gr.Markdown("## استخراج اقلام از فایل اکسل")
90
-
91
- with gr.Row():
92
- file_input = gr.File(label="آپلود فایل اکسل")
93
- upload_btn = gr.Button("📤 بارگذاری و ثبت")
94
-
95
- status_output = gr.Textbox(label="وضعیت", lines=2)
96
- constraints_output = gr.Textbox(label="🔍 قیود استخراج‌شده", lines=10)
97
-
98
- def handle_upload(file):
99
- if file is None:
100
- return "", "", "⚠️ لطفاً یک فایل اکسل انتخاب کنید."
101
- constraints, count, msg = parse_excel(file)
102
- joined = "\n".join(constraints) if constraints else ""
103
- return msg, joined
104
-
105
- upload_btn.click(handle_upload, inputs=[file_input], outputs=[status_output, constraints_output])
106
-
107
- with gr.TabItem("📂 بارگذاری فایل JSON"):
108
- gr.Markdown("## بارگذاری اولیه اطلاعات ذخیره‌شده")
109
-
110
- json_input = gr.File(label="فایل JSON")
111
- load_btn = gr.Button("📥 بارگذاری")
112
-
113
- load_status = gr.Textbox(label="نتیجه", lines=2)
114
- load_btn.click(load_json_file, inputs=[json_input], outputs=[load_status])
115
-
116
- with gr.TabItem("📑 نمایش اقلام ذخیره‌شده"):
117
- gr.Markdown("## فهرست اقلام ثبت‌شده در فایل JSON")
118
- refresh_btn = gr.Button("🔄 بازخوانی")
119
- json_display = gr.Textbox(label="موارد موجود", lines=20)
120
-
121
- refresh_btn.click(read_json_descriptions, outputs=[json_display])
122
 
123
  if __name__ == "__main__":
124
- demo.launch()
 
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": ["کد", "کد فهرست بها"],
 
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 = []
 
54
  else:
55
  existing = []
56
 
57
+ new_record = {
58
+ "project_description": description.strip(),
59
+ "items": materials
60
+ }
61
+ existing.append(new_record)
62
 
63
  with open(JSON_PATH, "w", encoding="utf-8") as f:
64
  json.dump(existing, f, indent=2, ensure_ascii=False)
65
 
66
  except Exception as e:
67
+ return "", "", f"❌ خطا در ذخیره فایل JSON: {str(e)}"
68
+
69
+ return "\n".join(constraints), f"✅ {len(materials)} قلم ثبت شد.", JSON_PATH
70
+
71
+ def download_json():
72
+ return JSON_PATH if os.path.exists(JSON_PATH) else None
73
 
74
+ def load_json_file(json_file):
75
+ if json_file is None:
76
+ return "⚠️ لطفاً یک فایل JSON معتبر انتخاب کنید."
77
 
 
78
  try:
79
+ with open(json_file.name, "r", encoding="utf-8") as f:
80
+ content = json.load(f)
81
+ with open(JSON_PATH, "w", encoding="utf-8") as f2:
82
+ json.dump(content, f2, indent=2, ensure_ascii=False)
83
+ return f"✅ فایل JSON بارگذاری و جایگزین شد."
84
  except Exception as e:
85
+ return f"❌ خطا در خواندن یا ذخیره فایل JSON: {str(e)}"
86
 
87
+ def show_all_projects():
88
  if not os.path.exists(JSON_PATH):
89
+ return "⚠️ فایل JSON موجود نیست."
90
+
91
  try:
92
  with open(JSON_PATH, "r", encoding="utf-8") as f:
93
+ content = json.load(f)
94
+ result = ""
95
+ for i, project in enumerate(content):
96
+ result += f"\n📁 پروژه {i+1}: {project['project_description']}\n"
97
+ for item in project["items"]:
98
+ result += f"- {item['description']} ({item['quantity']} {item['unit']})\n"
99
+ return result.strip()
100
  except Exception as e:
101
  return f"❌ خطا در خواندن فایل JSON: {str(e)}"
102
 
103
  with gr.Blocks(title="مدیریت مواد پروژه - نسخه 0.1.1") as demo:
104
+ with gr.Tab("📤 بارگذاری اکسل و ثبت پروژه"):
105
+ gr.Markdown("## آپلود فایل اکسل و وارد کردن توضیح پروژه")
106
+
107
+ with gr.Row():
108
+ file_input = gr.File(label="آپلود فایل اکسل")
109
+ project_desc = gr.Textbox(label="📝 توضیح پروژه")
110
+
111
+ upload_btn = gr.Button("📤 بارگذاری و ثبت")
112
+ status_output = gr.Textbox(label="وضعیت", lines=2)
113
+ constraints_output = gr.Textbox(label="🔍 اقلام استخراج‌شده", lines=10)
114
+ json_file_output = gr.File(label="📁 فایل JSON خروجی", visible=True)
115
+ download_btn = gr.Button("📥 دانلود فایل JSON")
116
+
117
+ upload_btn.click(parse_excel, inputs=[file_input, project_desc], outputs=[constraints_output, status_output, json_file_output])
118
+ download_btn.click(download_json, outputs=json_file_output)
119
+
120
+ with gr.Tab("📚 پروژه‌های ثبت‌شده و بارگذاری JSON"):
121
+ gr.Markdown("## مشاهده پروژه‌های ذخیره‌شده در فایل JSON")
122
+ show_btn = gr.Button("📂 نمایش پروژه‌های ذخیره‌شده")
123
+ json_content_output = gr.Textbox(label="📑 محتوای فایل JSON", lines=20, interactive=False)
124
+ show_btn.click(show_all_projects, outputs=json_content_output)
125
+
126
+ gr.Markdown("## بارگذاری فایل JSON از سیستم شما")
127
+ json_input_file = gr.File(label="📥 انتخاب فایل JSON جدید")
128
+ load_json_btn = gr.Button("🔄 بارگذاری فایل JSON جدید")
129
+ json_load_status = gr.Textbox(label="وضعیت بارگذاری فایل JSON")
130
+ load_json_btn.click(load_json_file, inputs=json_input_file, outputs=json_load_status)
 
 
 
 
 
 
 
 
131
 
132
  if __name__ == "__main__":
133
+ demo.launch()