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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 |
+
constraints.append(f"{material['description']} ({material['quantity']} {material['unit']})")
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
if os.path.exists(JSON_PATH):
|
| 52 |
+
with open(JSON_PATH, "r", encoding="utf-8") as f:
|
| 53 |
+
existing = json.load(f)
|
| 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(keyword=""):
|
| 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 |
+
|
| 95 |
+
keyword = keyword.strip().lower()
|
| 96 |
+
result = ""
|
| 97 |
+
for i, project in enumerate(content):
|
| 98 |
+
full_text = project["project_description"] + " " + " ".join([item["description"] for item in project["items"]])
|
| 99 |
+
if keyword and keyword not in full_text.lower():
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
result += f"\n📁 پروژه {i+1}: {project['project_description']}\n"
|
| 103 |
+
for item in project["items"]:
|
| 104 |
+
result += f"- {item['description']} ({item['quantity']} {item['unit']})\n"
|
| 105 |
+
return result.strip() or "❌ پروژهای با این کلیدواژه پیدا نشد."
|
| 106 |
+
except Exception as e:
|
| 107 |
+
return f"❌ خطا در خواندن فایل JSON: {str(e)}"
|
| 108 |
+
|
| 109 |
+
with gr.Blocks(title="مدیریت مواد پروژه - نسخه 0.1.2") as demo:
|
| 110 |
+
with gr.Tab("📤 بارگذاری اکسل و ثبت پروژه"):
|
| 111 |
+
gr.Markdown("## آپلود فایل اکسل و وارد کردن توضیح پروژه")
|
| 112 |
+
|
| 113 |
+
with gr.Row():
|
| 114 |
+
file_input = gr.File(label="آپلود فایل اکسل")
|
| 115 |
+
project_desc = gr.Textbox(label="📝 توضیح پروژه")
|
| 116 |
+
|
| 117 |
+
upload_btn = gr.Button("📤 بارگذاری و ثبت")
|
| 118 |
+
status_output = gr.Textbox(label="وضعیت", lines=2)
|
| 119 |
+
constraints_output = gr.Textbox(label="🔍 اقلام استخراجشده", lines=10)
|
| 120 |
+
json_file_output = gr.File(label="📁 فایل JSON خروجی", visible=True)
|
| 121 |
+
download_btn = gr.Button("📥 دانلود فایل JSON")
|
| 122 |
+
|
| 123 |
+
upload_btn.click(parse_excel, inputs=[file_input, project_desc], outputs=[constraints_output, status_output, json_file_output])
|
| 124 |
+
download_btn.click(download_json, outputs=json_file_output)
|
| 125 |
+
|
| 126 |
+
with gr.Tab("📚 پروژههای ثبتشده و بارگذاری JSON"):
|
| 127 |
+
gr.Markdown("## مشاهده پروژههای ذخیرهشده در فایل JSON")
|
| 128 |
+
show_btn = gr.Button("📂 نمایش پروژههای ذخیرهشده")
|
| 129 |
+
json_content_output = gr.Textbox(label="📑 محتوای فایل JSON", lines=20, interactive=False)
|
| 130 |
+
show_btn.click(show_all_projects, outputs=json_content_output)
|
| 131 |
+
|
| 132 |
+
gr.Markdown("## بارگذاری فایل JSON از سیستم شما")
|
| 133 |
+
json_input_file = gr.File(label="📥 انتخاب فایل JSON جدید")
|
| 134 |
+
load_json_btn = gr.Button("🔄 بارگذاری فایل JSON جدید")
|
| 135 |
+
json_load_status = gr.Textbox(label="وضعیت بارگذاری فایل JSON")
|
| 136 |
+
load_json_btn.click(load_json_file, inputs=json_input_file, outputs=json_load_status)
|
| 137 |
+
|
| 138 |
+
gr.Markdown("## جستجوی پروژهها با کلیدواژه")
|
| 139 |
+
search_box = gr.Textbox(label="🔍 کلیدواژه", placeholder="مثلاً کابل یا ترانس", lines=1)
|
| 140 |
+
search_btn = gr.Button("🔎 جستجو در پروژهها")
|
| 141 |
+
search_btn.click(show_all_projects, inputs=search_box, outputs=json_content_output)
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
demo.launch()
|