Reza-galaxy21 commited on
Commit
9e246b9
·
verified ·
1 Parent(s): 6824541

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import os
4
+ import json
5
+
6
+ # -----------------------
7
+ # تابع پردازش فایل اکسل
8
+ # -----------------------
9
+ def parse_excel_file(file):
10
+ try:
11
+ df = pd.read_excel(file.name, header=2) # شروع از سطر سوم
12
+ except Exception as e:
13
+ raise ValueError(f"❌ خطا در خواندن فایل اکسل: {str(e)}")
14
+
15
+ column_mapping = {
16
+ "کد": ["کد فهرست بها", "کد"],
17
+ "عنوان": ["عنوان", "شرح کالا", "نام کالا"],
18
+ "تعداد": ["تعداد", "تعداد مورد نیاز"],
19
+ "واحد": ["واحد", "واحد شمارش", "نوع واحد"]
20
+ }
21
+
22
+ resolved_columns = {}
23
+ for key, options in column_mapping.items():
24
+ found = next((col for col in options if col in df.columns), None)
25
+ if not found:
26
+ raise ValueError(f"❌ ستون «{key}» در فایل پیدا نشد.")
27
+ resolved_columns[key] = found
28
+
29
+ materials = []
30
+ for _, row in df.iterrows():
31
+ try:
32
+ quantity = float(row[resolved_columns["تعداد"]])
33
+ if pd.isna(quantity) or quantity <= 0:
34
+ continue
35
+ except:
36
+ continue
37
+
38
+ material = {
39
+ "code": str(row[resolved_columns["کد"]]).strip(),
40
+ "description": str(row[resolved_columns["عنوان"]]).strip(),
41
+ "quantity": quantity,
42
+ "unit": str(row[resolved_columns["واحد"]]).strip()
43
+ }
44
+ materials.append(material)
45
+
46
+ if not materials:
47
+ raise ValueError("⚠️ هیچ ماده‌ای با تعداد معتبر یافت نشد.")
48
+
49
+ return materials
50
+
51
+
52
+ # ----------------------------
53
+ # تابع ذخیره به فایل material_db.json
54
+ # ----------------------------
55
+ def save_materials_to_json(new_materials, project_description, json_path="material_db.json"):
56
+ if not os.path.exists(json_path):
57
+ with open(json_path, "w", encoding="utf-8") as f:
58
+ json.dump([], f, indent=2, ensure_ascii=False)
59
+
60
+ try:
61
+ with open(json_path, "r", encoding="utf-8") as f:
62
+ data = json.load(f)
63
+ except Exception as e:
64
+ raise ValueError(f"❌ خطا در خواندن فایل JSON: {str(e)}")
65
+
66
+ for record in data:
67
+ if record.get("description") == project_description:
68
+ raise ValueError("⚠️ پروژه‌ای با این توصیف قبلاً ثبت شده است.")
69
+
70
+ new_entry = {
71
+ "description": project_description,
72
+ "materials": new_materials
73
+ }
74
+ data.append(new_entry)
75
+
76
+ try:
77
+ with open(json_path, "w", encoding="utf-8") as f:
78
+ json.dump(data, f, indent=2, ensure_ascii=False)
79
+ except Exception as e:
80
+ raise ValueError(f"❌ خطا در ذخیره فایل JSON: {str(e)}")
81
+
82
+
83
+ # ---------------------
84
+ # هندل کلی پروژه
85
+ # ---------------------
86
+ def handle_project(file, description):
87
+ if not description.strip():
88
+ return "⚠️ لطفاً یک توصیف برای پروژه وارد کنید.", ""
89
+
90
+ try:
91
+ materials = parse_excel_file(file)
92
+ save_materials_to_json(materials, description)
93
+ constraint_output = "\n".join(
94
+ [f"🔹 {m['description']} (کد: {m['code']}، تعداد: {m['quantity']} {m['unit']})" for m in materials]
95
+ )
96
+ return "✅ مواد با موفقیت ثبت شدند.", constraint_output
97
+ except Exception as e:
98
+ return str(e), ""
99
+
100
+
101
+ # --------------------
102
+ # رابط کاربری با Gradio
103
+ # --------------------
104
+ with gr.Blocks(title="نسخه 0.0.3 - ثبت اقلام پروژه") as demo:
105
+ gr.Markdown("## 🧾 ثبت پروژه و استخراج اقلام کالا")
106
+
107
+ with gr.Row():
108
+ file_input = gr.File(label="📁 بارگذاری فایل اکسل", file_types=[".xls", ".xlsx"])
109
+ description_input = gr.Textbox(label="📝 توصیف پروژه", placeholder="مثلاً پروژه اصلاح تیرهای شکسته...")
110
+
111
+ submit_btn = gr.Button("📤 ثبت اطلاعات")
112
+ result_output = gr.Textbox(label="🧩 وضعیت", lines=2, interactive=False)
113
+ constraints_box = gr.Textbox(label="📌 قیود استخراج‌شده", lines=12, interactive=False)
114
+
115
+ submit_btn.click(
116
+ fn=handle_project,
117
+ inputs=[file_input, description_input],
118
+ outputs=[result_output, constraints_box]
119
+ )
120
+
121
+ # راه‌اندازی
122
+ if __name__ == "__main__":
123
+ demo.launch()