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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""program_V1.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/15rRG-Bc3sknJEpxsMIEje-2DKphRPL1Y
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import gradio as gr
|
| 12 |
+
import os
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
# إعداد المكتبات للرسم في الخلفية
|
| 17 |
+
plt.switch_backend('agg')
|
| 18 |
+
|
| 19 |
+
# --- دالة تحميل وتنظيف البيانات ---
|
| 20 |
+
def load_pro(file, col):
|
| 21 |
+
if not os.path.exists(file):
|
| 22 |
+
return pd.DataFrame()
|
| 23 |
+
try:
|
| 24 |
+
df = pd.read_csv(file, encoding='latin1')
|
| 25 |
+
p_col = next((c for c in df.columns if c.lower() in ['mrp', 'price']), None)
|
| 26 |
+
|
| 27 |
+
if p_col:
|
| 28 |
+
df['Price'] = df[p_col].astype(str).str.replace(r'[^\d.]', '', regex=True)
|
| 29 |
+
df['Price'] = pd.to_numeric(df['Price'], errors='coerce')
|
| 30 |
+
df = df.dropna(subset=['Price'])
|
| 31 |
+
df = df.rename(columns={col: 'Name'})
|
| 32 |
+
return df[['Name', 'Price']]
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"Error loading {file}: {e}")
|
| 35 |
+
return pd.DataFrame()
|
| 36 |
+
|
| 37 |
+
# --- دالة بناء التجميعة (نظام التوازن) ---
|
| 38 |
+
def ultimate_builder(budget, env_type):
|
| 39 |
+
# مصفوفة الملفات مع تحديد النسب المئوية للميزانية
|
| 40 |
+
files = {
|
| 41 |
+
"CPU": ("CPU.csv", "CPU", 0.15),
|
| 42 |
+
"GPU": ("GPU.csv", "GPU", 0.25),
|
| 43 |
+
"MOBO": ("MotherBoard.csv", "motherBoard", 0.08),
|
| 44 |
+
"RAM": ("RAM.csv", "Ram", 0.05),
|
| 45 |
+
"SSD": ("StorageSSD.csv", "SSD", 0.05),
|
| 46 |
+
"PSU": ("PowerSupply.csv", "PowerSupply", 0.05),
|
| 47 |
+
"CASE": ("cabinates.csv", "cabinates", 0.04),
|
| 48 |
+
"ACC": ("Accessories.csv", "Name", 0.03)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# اختيار نوع العرض بناءً على المكان
|
| 52 |
+
disp_file = "Monitors.csv" if "مكتب" in env_type else "TVs.csv"
|
| 53 |
+
files["DISPLAY"] = (disp_file, "Name", 0.10)
|
| 54 |
+
|
| 55 |
+
final_parts = []
|
| 56 |
+
total = 0
|
| 57 |
+
|
| 58 |
+
for cat, (file, col, ratio) in files.items():
|
| 59 |
+
df = load_pro(file, col)
|
| 60 |
+
if not df.empty:
|
| 61 |
+
limit = budget * ratio
|
| 62 |
+
affordable = df[df['Price'] <= limit]
|
| 63 |
+
|
| 64 |
+
if not affordable.empty:
|
| 65 |
+
# يختار أفضل قطعة تناسب هذه الميزانية
|
| 66 |
+
selected = affordable.sort_values('Price', ascending=False).iloc[0]
|
| 67 |
+
else:
|
| 68 |
+
# إذا لم يجد، يختار أرخص قطعة موجودة
|
| 69 |
+
selected = df.sort_values('Price', ascending=True).iloc[0]
|
| 70 |
+
|
| 71 |
+
label = "الشاشة" if cat == "DISPLAY" else "الملحقات" if cat == "ACC" else cat
|
| 72 |
+
final_parts.append([label, selected['Name'], f"{selected['Price']:,.2f}"])
|
| 73 |
+
total += selected['Price']
|
| 74 |
+
else:
|
| 75 |
+
final_parts.append([cat, f"ملف {file} غير متوفر", "0.00"])
|
| 76 |
+
|
| 77 |
+
# تقرير الحالة النهائي
|
| 78 |
+
status = "⚠️ (تجاوزت الميزانية)" if total > budget else "✅ (ضمن الميزانية)"
|
| 79 |
+
report = f"### ملخص التجميعة المهندسة {status}\n- **الميزانية المطلوبة:** {budget:,.2f} دولار\n- **التكلفة الفعلية:** {total:,.2f} دولار\n- **مكان التشغيل:** {env_type}"
|
| 80 |
+
|
| 81 |
+
return final_parts, report
|
| 82 |
+
|
| 83 |
+
# --- واجهة المستخدم (Gradio) ---
|
| 84 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
|
| 85 |
+
gr.Markdown("# 🖥️ نظام المهندس التقني المتكامل - الإصدار الثاني")
|
| 86 |
+
gr.Markdown("### نظام موازنة القطع حسب الميزانية المتاحة")
|
| 87 |
+
|
| 88 |
+
with gr.Row():
|
| 89 |
+
with gr.Column(scale=1):
|
| 90 |
+
in_budget = gr.Number(label="الميزانية الإجمالية (USD)", value=1500)
|
| 91 |
+
in_env = gr.Dropdown(["غرفة مكتب (Monitor)", "صالة معيشة (TV)"], label="مكان الجهاز", value="غرفة مكتب (Monitor)")
|
| 92 |
+
btn = gr.Button("توليد التجميعة", variant="primary")
|
| 93 |
+
|
| 94 |
+
with gr.Column(scale=2):
|
| 95 |
+
out_table = gr.DataFrame(headers=["الفئة", "القطعة", "السعر ($)"])
|
| 96 |
+
out_text = gr.Markdown()
|
| 97 |
+
|
| 98 |
+
# ربط الزر بالدالة (تم إزالة in_mode من هنا أيضاً)
|
| 99 |
+
btn.click(fn=ultimate_builder, inputs=[in_budget, in_env], outputs=[out_table, out_text])
|
| 100 |
+
|
| 101 |
+
# إطلاق الواجهة
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
demo.launch()
|
| 104 |
+
|
| 105 |
+
import pandas as pd
|
| 106 |
+
import numpy as np
|
| 107 |
+
import matplotlib.pyplot as plt
|
| 108 |
+
|
| 109 |
+
# Step 1: استيراد المكتبات اللازمة
|
| 110 |
+
import pandas as pd
|
| 111 |
+
|
| 112 |
+
# Step 2: تحميل الملف من Google Drive باستخدام معرف الملف (ID)
|
| 113 |
+
# سيتم تحميل الملف وحفظه باسم diabetes.csv في مسار الكولاب
|
| 114 |
+
!gdown --id 1K_DIJCo01zZvNNxeiqjB1XX62IbKPws3
|
| 115 |
+
|
| 116 |
+
# Step 3: قراءة الملف وتحويله إلى DataFrame
|
| 117 |
+
# ملاحظة: إذا واجهت مشكلة في التشفير، يفضل إضافة encoding='latin1'
|
| 118 |
+
df = pd.read_csv('CPU.csv')
|
| 119 |
+
df = pd.read_csv('Accessories.csv')
|
| 120 |
+
df = pd.read_csv('cabinates.csv')
|
| 121 |
+
df = pd.read_csv('GPU.csv')
|
| 122 |
+
df = pd.read_csv('Monitors.csv')
|
| 123 |
+
df = pd.read_csv('MotherBoard.csv')
|
| 124 |
+
df = pd.read_csv('PowerSupply.csv')
|
| 125 |
+
df = pd.read_csv('RAM.csv')
|
| 126 |
+
df = pd.read_csv('StorageSSD.csv')
|
| 127 |
+
df = pd.read_csv('TVs.csv')
|
| 128 |
+
# Step 4: عرض البيانات للتأكد من نجاح العملية
|
| 129 |
+
print("تم تحميل البيانات بنجاح! إليك أول 5 أسطر:")
|
| 130 |
+
df.head()
|
| 131 |
+
|
| 132 |
+
# Step 1: تحميل البيانات (يجب تشغيل هذا الجزء أولاً)
|
| 133 |
+
import pandas as pd
|
| 134 |
+
|
| 135 |
+
# تحميل الملف
|
| 136 |
+
!gdown --id 1K_DIJCo01zZvNNxeiqjB1XX62IbKPws3
|
| 137 |
+
df = pd.read_csv('diabetes.csv')
|
| 138 |
+
|
| 139 |
+
# ---------------------------------------------------------
|
| 140 |
+
# step 2 : Discover Data
|
| 141 |
+
|
| 142 |
+
print("--- 1. Dataset Shape (Rows, Columns) ---")
|
| 143 |
+
print(df.shape)
|
| 144 |
+
|
| 145 |
+
print("\n--- 2. Columns Names ---")
|
| 146 |
+
print(df.columns.tolist())
|
| 147 |
+
|
| 148 |
+
print("\n--- 3. Data Types ---")
|
| 149 |
+
print(df.dtypes)
|
| 150 |
+
|
| 151 |
+
print("\n--- 4. Statistical Summary ---")
|
| 152 |
+
# يظهر الإحصائيات للأرقام (المتوسط، أقل قيمة، أعلى قيمة)
|
| 153 |
+
display(df.describe())
|
| 154 |
+
|
| 155 |
+
# step 2 : Discover Data - Columns Analysis
|
| 156 |
+
|
| 157 |
+
# 1. عرض أسماء الأعمدة (Columns Names)
|
| 158 |
+
print("--- List of Columns in Dataset ---")
|
| 159 |
+
print(df.columns.tolist())
|
| 160 |
+
|
| 161 |
+
# 2. عرض أنواع البيانات لكل عمود (Data Types)
|
| 162 |
+
# يساعدك لتعرف هل السعر رقم (float/int) أم نص (object)
|
| 163 |
+
print("\n--- Columns Data Types ---")
|
| 164 |
+
print(df.dtypes)
|
| 165 |
+
|
| 166 |
+
# 3. عرض عينة من البيانات للأعمدة المكتشفة
|
| 167 |
+
print("\n--- First 3 Rows for these Columns ---")
|
| 168 |
+
display(df.head(3))
|
| 169 |
+
|
| 170 |
+
import pandas as pd
|
| 171 |
+
import os
|
| 172 |
+
|
| 173 |
+
# 1. قائمة بملفات التجميعة الخاصة بك
|
| 174 |
+
files = {
|
| 175 |
+
"المعالجات": "CPU.csv",
|
| 176 |
+
"كروت الشاشة": "GPU.csv",
|
| 177 |
+
"الرامات": "RAM.csv",
|
| 178 |
+
"التخزين": "StorageSSD.csv"
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
print("=== 📊 فحص هيكل الداتا سيت الخاصة بالتجميعات (df.info) ===\n")
|
| 182 |
+
|
| 183 |
+
for label, path in files.items():
|
| 184 |
+
if os.path.exists(path):
|
| 185 |
+
try:
|
| 186 |
+
# قراءة الملف مع معالجة التشفير لضمان عدم حدوث خطأ
|
| 187 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 188 |
+
|
| 189 |
+
print(f"🔍 فحص ملف: {label} ({path})")
|
| 190 |
+
|
| 191 |
+
# تنفيذ df.info()
|
| 192 |
+
df_temp.info()
|
| 193 |
+
|
| 194 |
+
print("-" * 50)
|
| 195 |
+
except Exception as e:
|
| 196 |
+
print(f"❌ تعذر فحص {label}: {e}")
|
| 197 |
+
else:
|
| 198 |
+
print(f"⚠️ الملف {path} غير موجود في المسار الحالي.")
|
| 199 |
+
|
| 200 |
+
import pandas as pd
|
| 201 |
+
import os
|
| 202 |
+
|
| 203 |
+
# 1. قائمة ملفات مشروعك (الداتا سيت الخاصة بك)
|
| 204 |
+
files = {
|
| 205 |
+
"CPU": "CPU.csv",
|
| 206 |
+
"GPU": "GPU.csv",
|
| 207 |
+
"RAM": "RAM.csv",
|
| 208 |
+
"SSD": "StorageSSD.csv"
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
print("=== 📈 الإحصائيات الوصفية لبيانات التجميعات (df.describe) ===\n")
|
| 212 |
+
|
| 213 |
+
for label, path in files.items():
|
| 214 |
+
if os.path.exists(path):
|
| 215 |
+
try:
|
| 216 |
+
# قراءة الملف
|
| 217 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 218 |
+
|
| 219 |
+
# تنظيف عمود السعر لتحويله لرقم (لأن describe تعمل فقط على الأرقام)
|
| 220 |
+
p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 221 |
+
|
| 222 |
+
if p_col:
|
| 223 |
+
# إزالة أي رموز غير رقمية وتحويل العمود إلى float
|
| 224 |
+
df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(r'[^\d.]', '', regex=True), errors='coerce')
|
| 225 |
+
|
| 226 |
+
print(f"📊 إحصائيات ملف: {label}")
|
| 227 |
+
|
| 228 |
+
# تنفيذ describe وعرض النتائج بتنسيق منظم
|
| 229 |
+
# استخدمنا .round(2) لتقريب الأرقام لخانة مئوية واحدة
|
| 230 |
+
display(df_temp.describe().round(2))
|
| 231 |
+
|
| 232 |
+
print("-" * 60 + "\n")
|
| 233 |
+
|
| 234 |
+
except Exception as e:
|
| 235 |
+
print(f"❌ خطأ في تحليل {label}: {e}")
|
| 236 |
+
else:
|
| 237 |
+
print(f"⚠️ الملف {path} غير موجود.\n")
|
| 238 |
+
|
| 239 |
+
import pandas as pd
|
| 240 |
+
import os
|
| 241 |
+
|
| 242 |
+
# 1. قائمة ملفات التجميعة الخاصة بك
|
| 243 |
+
files = {
|
| 244 |
+
"المعالجات": "CPU.csv",
|
| 245 |
+
"كروت الشاشة": "GPU.csv",
|
| 246 |
+
"الرامات": "RAM.csv",
|
| 247 |
+
"اللوحة الأم": "MotherBoard.csv",
|
| 248 |
+
"التخزين": "StorageSSD.csv"
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
print("=== 🧹 خطوة تنظيف البيانات: فحص القيم المفقودة (isnull) ===\n")
|
| 252 |
+
|
| 253 |
+
for label, path in files.items():
|
| 254 |
+
if os.path.exists(path):
|
| 255 |
+
try:
|
| 256 |
+
# قراءة الملف
|
| 257 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 258 |
+
|
| 259 |
+
print(f"📍 فحص ملف {label}:")
|
| 260 |
+
|
| 261 |
+
# حساب عدد القيم المفقودة في كل عمود
|
| 262 |
+
missing_count = df_temp.isnull().sum()
|
| 263 |
+
|
| 264 |
+
# عرض الأعمدة التي تحتوي على قيم مفقودة فقط لتسهيل القراءة
|
| 265 |
+
if missing_count.sum() > 0:
|
| 266 |
+
print(missing_count[missing_count > 0])
|
| 267 |
+
else:
|
| 268 |
+
print("✅ لا توجد قيم مفقودة في هذا الملف.")
|
| 269 |
+
|
| 270 |
+
print("-" * 40)
|
| 271 |
+
|
| 272 |
+
except Exception as e:
|
| 273 |
+
print(f"❌ خطأ أثناء فحص {label}: {e}")
|
| 274 |
+
else:
|
| 275 |
+
print(f"⚠️ الملف {path} غير موجود.")
|
| 276 |
+
|
| 277 |
+
import pandas as pd
|
| 278 |
+
import matplotlib.pyplot as plt
|
| 279 |
+
import os
|
| 280 |
+
|
| 281 |
+
# 1. قائمة ملفات الداتا سيت الخاصة بك
|
| 282 |
+
files = {
|
| 283 |
+
"CPU": "CPU.csv",
|
| 284 |
+
"GPU": "GPU.csv",
|
| 285 |
+
"RAM": "RAM.csv",
|
| 286 |
+
"SSD": "StorageSSD.csv"
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
# 2. إعداد الشكل (Figure) ليحتوي على رسومات متعددة
|
| 290 |
+
plt.figure(figsize=(16, 8))
|
| 291 |
+
|
| 292 |
+
plot_index = 1
|
| 293 |
+
for label, path in files.items():
|
| 294 |
+
if os.path.exists(path):
|
| 295 |
+
try:
|
| 296 |
+
# قراءة الملف وتنظيف السعر لتحويله لرقم فقط للرسم
|
| 297 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 298 |
+
p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 299 |
+
|
| 300 |
+
if p_col:
|
| 301 |
+
# تحويل السعر لرقم (إزالة أي رموز غير رقمية)
|
| 302 |
+
df_temp['Price_Numeric'] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(r'[^\d.]', '', regex=True), errors='coerce')
|
| 303 |
+
df_temp = df_temp.dropna(subset=['Price_Numeric'])
|
| 304 |
+
|
| 305 |
+
# إضافة رسم فرعي (Subplot) لكل ملف
|
| 306 |
+
plt.subplot(1, 4, plot_index)
|
| 307 |
+
df_temp.boxplot(column=['Price_Numeric'])
|
| 308 |
+
plt.title(f"Outliers in {label}")
|
| 309 |
+
plot_index += 1
|
| 310 |
+
except Exception as e:
|
| 311 |
+
print(f"Error plotting {label}: {e}")
|
| 312 |
+
|
| 313 |
+
plt.tight_layout()
|
| 314 |
+
plt.show()
|
| 315 |
+
|
| 316 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 317 |
+
import pandas as pd
|
| 318 |
+
import matplotlib.pyplot as plt
|
| 319 |
+
import os
|
| 320 |
+
|
| 321 |
+
# تفعيل الرسم في مخرجات الخلية
|
| 322 |
+
# %matplotlib inline
|
| 323 |
+
|
| 324 |
+
# أسماء الملفات التي تريد تحليلها
|
| 325 |
+
files = {
|
| 326 |
+
"CPU": "CPU.csv",
|
| 327 |
+
"GPU": "GPU.csv",
|
| 328 |
+
"RAM": "RAM.csv",
|
| 329 |
+
"SSD": "StorageSSD.csv"
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
data_to_plot = {}
|
| 333 |
+
|
| 334 |
+
# قراءة وتنظيف البيانات
|
| 335 |
+
for label, path in files.items():
|
| 336 |
+
if os.path.exists(path):
|
| 337 |
+
try:
|
| 338 |
+
# استخدام encoding='latin1' لتجنب أخطاء التشفير
|
| 339 |
+
df = pd.read_csv(path, encoding='latin1')
|
| 340 |
+
|
| 341 |
+
# البحث عن عمود السعر (Price or MRP)
|
| 342 |
+
p_col = next((c for c in df.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 343 |
+
|
| 344 |
+
if p_col:
|
| 345 |
+
# تحويل السعر لرقم وتنظيفه من الفواصل
|
| 346 |
+
prices = pd.to_numeric(df[p_col].astype(str).str.replace(',', '').str.replace('$', ''), errors='coerce').dropna()
|
| 347 |
+
if not prices.empty:
|
| 348 |
+
data_to_plot[label] = prices / 22 # التحويل للدولار
|
| 349 |
+
except:
|
| 350 |
+
continue
|
| 351 |
+
|
| 352 |
+
# إنشاء الصورة (Boxplot)
|
| 353 |
+
if data_to_plot:
|
| 354 |
+
# دمج البيانات في جدول واحد لضمان ظهورها في "صورة واحدة"
|
| 355 |
+
df_plot = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in data_to_plot.items()]))
|
| 356 |
+
|
| 357 |
+
# تحديد حجم الصورة (Width=14, Height=6)
|
| 358 |
+
plt.figure(figsize=(14, 6))
|
| 359 |
+
|
| 360 |
+
# رسم الصندوق مع تسميات بالإنجليزية
|
| 361 |
+
df_plot.boxplot()
|
| 362 |
+
|
| 363 |
+
# إضافة العناوين بالإنجليزية لضمان وضوح الخط
|
| 364 |
+
plt.title("Price Distribution and Outliers Analysis", fontsize=15)
|
| 365 |
+
plt.xlabel("Component Type", fontsize=12)
|
| 366 |
+
plt.ylabel("Price in USD ($)", fontsize=12)
|
| 367 |
+
|
| 368 |
+
# تحسين مظهر الشبكة
|
| 369 |
+
plt.grid(axis='y', linestyle='--', alpha=0.7)
|
| 370 |
+
|
| 371 |
+
# إظهار الصورة النهائية (سيظهر مخطط واحد فقط)
|
| 372 |
+
plt.show()
|
| 373 |
+
else:
|
| 374 |
+
print("No data found! Please upload CSV files to the side panel.")
|
| 375 |
+
|
| 376 |
+
import pandas as pd
|
| 377 |
+
import matplotlib.pyplot as plt
|
| 378 |
+
import os
|
| 379 |
+
|
| 380 |
+
# 1. تحميل ملف المعالجات كمثال (أو أي ملف تريد دراسة العلاقة فيه)
|
| 381 |
+
file_path = 'CPU.csv'
|
| 382 |
+
|
| 383 |
+
if os.path.exists(file_path):
|
| 384 |
+
try:
|
| 385 |
+
# القراءة بتشفير latin1 لتجنب الأخطاء السابقة
|
| 386 |
+
df = pd.read_csv(file_path, encoding='latin1')
|
| 387 |
+
|
| 388 |
+
# تنظيف عمود السعر (سنعتبره المتغير Y)
|
| 389 |
+
p_col = next((c for c in df.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 390 |
+
|
| 391 |
+
if p_col:
|
| 392 |
+
# تحويل السعر لرقم وتنظيفه
|
| 393 |
+
df['Price_Clean'] = pd.to_numeric(df[p_col].astype(str).str.replace(',', '').str.replace('$', ''), errors='coerce')
|
| 394 |
+
|
| 395 |
+
# نختار متغير آخر للعلاقة (مثلاً الترتيب أو القوة إذا وجدت أرقام أخرى)
|
| 396 |
+
# هنا سنرسم العلاقة بين "ترتيب القطعة في القائمة" وسعرها كمثال تقريبي
|
| 397 |
+
df['Index'] = range(len(df))
|
| 398 |
+
|
| 399 |
+
# 2. إنشاء الرسم البياني (Scatter Plot)
|
| 400 |
+
plt.figure(figsize=(8, 6))
|
| 401 |
+
|
| 402 |
+
# رسم العلاقة (x هو الترتيب، y هو السعر)
|
| 403 |
+
plt.scatter(df['Index'], df['Price_Clean'], color='blue', alpha=0.5)
|
| 404 |
+
|
| 405 |
+
# التسميات بالإنجليزية لضمان ظهورها
|
| 406 |
+
plt.xlabel("Item Index")
|
| 407 |
+
plt.ylabel("Price in USD ($)")
|
| 408 |
+
plt.title("Relationship between Product Index and Price")
|
| 409 |
+
|
| 410 |
+
plt.grid(True, linestyle='--', alpha=0.6)
|
| 411 |
+
|
| 412 |
+
# إظهار الصورة
|
| 413 |
+
plt.show()
|
| 414 |
+
else:
|
| 415 |
+
print("Price column not found in the CSV!")
|
| 416 |
+
except Exception as e:
|
| 417 |
+
print(f"Error: {e}")
|
| 418 |
+
else:
|
| 419 |
+
print("File CPU.csv not found!")
|
| 420 |
+
|
| 421 |
+
# Step 1: استيراد المكتبات الضرورية
|
| 422 |
+
import pandas as pd
|
| 423 |
+
import numpy as np
|
| 424 |
+
import matplotlib.pyplot as plt
|
| 425 |
+
|
| 426 |
+
# Step 2: تحميل ملفاتك (استخدم الـ ID الخاص بملفاتك من جوجل درايف)
|
| 427 |
+
# ملاحظة: استبدل الـ ID بالمعرف الخاص بملف CPU.csv مثلاً
|
| 428 |
+
!gdown --id 1K_DIJCo01zZvNNxeiqjB1XX62IbKPws3
|
| 429 |
+
|
| 430 |
+
# Step 3: قراءة الملف ومعالجة مشكلة التشفير (Unicode Error)
|
| 431 |
+
try:
|
| 432 |
+
# قمنا بتغيير اسم الملف ليتناسب مع ما حملته
|
| 433 |
+
df = pd.read_csv('CPU.csv', encoding='latin1')
|
| 434 |
+
print("Success: File loaded successfully!")
|
| 435 |
+
except:
|
| 436 |
+
# في حال لم يجد ملف CPU، سيقرأ الملف الافتراضي الذي حملته للتجربة
|
| 437 |
+
df = pd.read_csv('diabetes.csv')
|
| 438 |
+
print("Note: Loaded diabetes.csv as a fallback.")
|
| 439 |
+
|
| 440 |
+
# Step 4: عرض أول 5 أسطر للتأكد من البيانات (مثل ملف diabetes)
|
| 441 |
+
print(df.head())
|
| 442 |
+
|
| 443 |
+
# Step 5: تنظيف عمود السعر (Price) ليصبح رقمياً للرسم البياني
|
| 444 |
+
if 'Price' in df.columns or 'MRP' in df.columns:
|
| 445 |
+
p_col = 'Price' if 'Price' in df.columns else 'MRP'
|
| 446 |
+
df[p_col] = pd.to_numeric(df[p_col].astype(str).str.replace(',', ''), errors='coerce')
|
| 447 |
+
|
| 448 |
+
# رسم مخطط الصندوق (Boxplot) للسعر فقط
|
| 449 |
+
plt.figure(figsize=(10, 6))
|
| 450 |
+
df.boxplot(column=[p_col])
|
| 451 |
+
plt.title(f"Price Distribution Analysis (Outliers)")
|
| 452 |
+
plt.ylabel("Price in local currency")
|
| 453 |
+
plt.show()
|
| 454 |
+
|
| 455 |
+
import pandas as pd
|
| 456 |
+
import os
|
| 457 |
+
|
| 458 |
+
# 1. تحميل ملف المعالجات كمثال
|
| 459 |
+
file_path = 'CPU.csv'
|
| 460 |
+
|
| 461 |
+
if os.path.exists(file_path):
|
| 462 |
+
# قراءة الملف مع معالجة التشفير
|
| 463 |
+
df = pd.read_csv(file_path, encoding='latin1')
|
| 464 |
+
|
| 465 |
+
print("--- Step 2: Discover Data ---")
|
| 466 |
+
|
| 467 |
+
# معرفة حجم البيانات (Rows, Columns)
|
| 468 |
+
shape = df.shape
|
| 469 |
+
print(f"Dataset Shape: {shape}")
|
| 470 |
+
print(f"Number of Items (Rows): {shape[0]}")
|
| 471 |
+
print(f"Number of Features (Columns): {shape[1]}")
|
| 472 |
+
|
| 473 |
+
print("\n--- Column Names ---")
|
| 474 |
+
print(df.columns.tolist()) # عرض أسماء الأعمدة لمعرفة المواصفات المتاحة
|
| 475 |
+
|
| 476 |
+
print("\n--- Quick Statistics ---")
|
| 477 |
+
# هذا السطر يعطيك (المتوسط، أقل سعر، أعلى سعر) للأعمدة الرقمية
|
| 478 |
+
print(df.describe())
|
| 479 |
+
else:
|
| 480 |
+
print("Please upload CPU.csv first!")
|
| 481 |
+
|
| 482 |
+
import pandas as pd
|
| 483 |
+
import os
|
| 484 |
+
|
| 485 |
+
# 1. قائمة بالملفات التي تشكل الداتا سيت الخاصة بك
|
| 486 |
+
files = {
|
| 487 |
+
"CPU": "CPU.csv",
|
| 488 |
+
"GPU": "GPU.csv",
|
| 489 |
+
"RAM": "RAM.csv",
|
| 490 |
+
"SSD": "StorageSSD.csv"
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
print("=== Full Dataset Discovery ===\n")
|
| 494 |
+
|
| 495 |
+
for label, path in files.items():
|
| 496 |
+
if os.path.exists(path):
|
| 497 |
+
try:
|
| 498 |
+
# قراءة الملف مع معالجة التشفير (لتجنب خطأ Unicode السابق)
|
| 499 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 500 |
+
|
| 501 |
+
print(f"--- Analysis for: {label} ---")
|
| 502 |
+
|
| 503 |
+
# تنفيذ أمر shape (عدد الصفوف والأعمدة)
|
| 504 |
+
rows, cols = df_temp.shape
|
| 505 |
+
print(f"Shape: {rows} Items and {cols} Features")
|
| 506 |
+
|
| 507 |
+
# عرض أسماء الأعمدة لمعرفة نوع المواصفات
|
| 508 |
+
print(f"Columns: {df_temp.columns.tolist()}")
|
| 509 |
+
|
| 510 |
+
# إحصائيات سريعة للأسعار (المتوسط، أقل سعر، أعلى سعر)
|
| 511 |
+
p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 512 |
+
if p_col:
|
| 513 |
+
# تنظيف السعر لتحويله لرقم
|
| 514 |
+
df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', ''), errors='coerce')
|
| 515 |
+
print(f"Price Statistics (in USD/Local):\n{df_temp[p_col].describe()}")
|
| 516 |
+
|
| 517 |
+
print("-" * 30 + "\n")
|
| 518 |
+
except Exception as e:
|
| 519 |
+
print(f"Could not analyze {label}: {e}\n")
|
| 520 |
+
else:
|
| 521 |
+
print(f"File {path} not found. Please upload it.\n")
|
| 522 |
+
|
| 523 |
+
import pandas as pd
|
| 524 |
+
import os
|
| 525 |
+
|
| 526 |
+
# قائمة ملفات مشروعك
|
| 527 |
+
files = {
|
| 528 |
+
"CPU": "CPU.csv",
|
| 529 |
+
"GPU": "GPU.csv",
|
| 530 |
+
"RAM": "RAM.csv",
|
| 531 |
+
"SSD": "StorageSSD.csv"
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
print("=== Discovering Data: df.info() for all datasets ===\n")
|
| 535 |
+
|
| 536 |
+
for label, path in files.items():
|
| 537 |
+
if os.path.exists(path):
|
| 538 |
+
try:
|
| 539 |
+
# القراءة مع معالجة التشفير لتجنب الأخطاء
|
| 540 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 541 |
+
|
| 542 |
+
print(f"--- INFO FOR: {label} ---")
|
| 543 |
+
|
| 544 |
+
# تنفيذ أمر info() لعرض أنواع البيانات والقيم المفقودة
|
| 545 |
+
# أضفنا buf=None لإظهار المخرج مباشرة في كولاب
|
| 546 |
+
df_temp.info()
|
| 547 |
+
|
| 548 |
+
print("\n" + "="*50 + "\n")
|
| 549 |
+
except Exception as e:
|
| 550 |
+
print(f"Error reading {label}: {e}")
|
| 551 |
+
else:
|
| 552 |
+
print(f"File {path} not found.\n")
|
| 553 |
+
|
| 554 |
+
import pandas as pd
|
| 555 |
+
import os
|
| 556 |
+
|
| 557 |
+
# قائمة ملفات مشروعك
|
| 558 |
+
files = {
|
| 559 |
+
"CPU": "CPU.csv",
|
| 560 |
+
"GPU": "GPU.csv",
|
| 561 |
+
"RAM": "RAM.csv",
|
| 562 |
+
"SSD": "StorageSSD.csv"
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
print("=== Step 2: Full Statistical Discovery (df.describe) ===\n")
|
| 566 |
+
|
| 567 |
+
for label, path in files.items():
|
| 568 |
+
if os.path.exists(path):
|
| 569 |
+
try:
|
| 570 |
+
# قراءة الملف مع معالجة التشفير
|
| 571 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 572 |
+
|
| 573 |
+
# البحث عن عمود السعر وتنظيفه (لأن describe تعمل فقط على الأرقام)
|
| 574 |
+
p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 575 |
+
|
| 576 |
+
if p_col:
|
| 577 |
+
# تحويل السعر لرقم (إزالة الفواصل والعلامات)
|
| 578 |
+
df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', '').str.replace('$', ''), errors='coerce')
|
| 579 |
+
|
| 580 |
+
print(f"--- Statistics for {label} ---")
|
| 581 |
+
# إظهار الإحصائيات لعمود السعر
|
| 582 |
+
print(df_temp[p_col].describe())
|
| 583 |
+
print("\n" + "="*40 + "\n")
|
| 584 |
+
except Exception as e:
|
| 585 |
+
print(f"Error analyzing {label}: {e}")
|
| 586 |
+
|
| 587 |
+
import pandas as pd
|
| 588 |
+
import os
|
| 589 |
+
|
| 590 |
+
# قائمة ملفات مشروعك
|
| 591 |
+
files = {
|
| 592 |
+
"CPU": "CPU.csv",
|
| 593 |
+
"GPU": "GPU.csv",
|
| 594 |
+
"RAM": "RAM.csv",
|
| 595 |
+
"SSD": "StorageSSD.csv"
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
print("=== Step 3: Cleaning Data (Checking Missing Values) ===\n")
|
| 599 |
+
|
| 600 |
+
for label, path in files.items():
|
| 601 |
+
if os.path.exists(path):
|
| 602 |
+
try:
|
| 603 |
+
# القراءة مع معالجة التشفير
|
| 604 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 605 |
+
|
| 606 |
+
print(f"--- Missing Values in {label} ---")
|
| 607 |
+
|
| 608 |
+
# تنفيذ أمر isnull().sum() لمعرفة عدد الفراغات في كل عمود
|
| 609 |
+
missing_data = df_temp.isnull().sum()
|
| 610 |
+
|
| 611 |
+
# إظهار الأعمدة التي تحتوي على مفقودات فقط لتسهيل القراءة
|
| 612 |
+
if missing_data.sum() > 0:
|
| 613 |
+
print(missing_data[missing_data > 0])
|
| 614 |
+
else:
|
| 615 |
+
print("Perfect! No missing values found in this file.")
|
| 616 |
+
|
| 617 |
+
print("\n" + "="*40 + "\n")
|
| 618 |
+
except Exception as e:
|
| 619 |
+
print(f"Error analyzing {label}: {e}")
|
| 620 |
+
|
| 621 |
+
import pandas as pd
|
| 622 |
+
import os
|
| 623 |
+
|
| 624 |
+
# 1. تعريف دالة اكتشاف ومعالجة القيم المتطرفة (IQR Method)
|
| 625 |
+
def handle_outliers_with_mean(df, column):
|
| 626 |
+
# التأكد أن العمود رقمي فقط
|
| 627 |
+
if pd.api.types.is_numeric_dtype(df[column]):
|
| 628 |
+
Q1 = df[column].quantile(0.25)
|
| 629 |
+
Q3 = df[column].quantile(0.75)
|
| 630 |
+
IQR = Q3 - Q1
|
| 631 |
+
lower_bound = Q1 - 1.5 * IQR
|
| 632 |
+
upper_bound = Q3 + 1.5 * IQR
|
| 633 |
+
|
| 634 |
+
# استبدال القيم المتطرفة بمتوسط العمود (Mean)
|
| 635 |
+
mean_value = df[column].mean()
|
| 636 |
+
df.loc[(df[column] < lower_bound) | (df[column] > upper_bound), column] = mean_value
|
| 637 |
+
return df
|
| 638 |
+
|
| 639 |
+
# 2. تطبيق العملية على كل ملفات مشروعك
|
| 640 |
+
files = {"CPU": "CPU.csv", "GPU": "GPU.csv", "RAM": "RAM.csv", "SSD": "StorageSSD.csv"}
|
| 641 |
+
|
| 642 |
+
print("=== Step 3: Cleaning Outliers and Replacing with Mean ===\n")
|
| 643 |
+
|
| 644 |
+
for label, path in files.items():
|
| 645 |
+
if os.path.exists(path):
|
| 646 |
+
try:
|
| 647 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 648 |
+
|
| 649 |
+
# تنظيف عمود السعر أولاً ليصبح رقمياً
|
| 650 |
+
p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 651 |
+
if p_col:
|
| 652 |
+
df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', ''), errors='coerce')
|
| 653 |
+
df_temp[p_col] = df_temp[p_col].fillna(df_temp[p_col].mean()) # تعبئة الفراغات بالمتوسط
|
| 654 |
+
|
| 655 |
+
# تطبيق الدالة على عمود السعر
|
| 656 |
+
df_temp = handle_outliers_with_mean(df_temp, p_col)
|
| 657 |
+
print(f"Success: Outliers handled in {label} ({p_col})")
|
| 658 |
+
|
| 659 |
+
except Exception as e:
|
| 660 |
+
print(f"Error in {label}: {e}")
|
| 661 |
+
|
| 662 |
+
print("\nDone! All outliers have been normalized.")
|
| 663 |
+
|
| 664 |
+
import pandas as pd
|
| 665 |
+
import matplotlib.pyplot as plt
|
| 666 |
+
import os
|
| 667 |
+
|
| 668 |
+
# 1. تجميع البيانات المنظفة (بعد معالجة القيم المتطرفة)
|
| 669 |
+
cleaned_plot_data = {}
|
| 670 |
+
|
| 671 |
+
for label, path in files.items():
|
| 672 |
+
if os.path.exists(path):
|
| 673 |
+
try:
|
| 674 |
+
df_temp = pd.read_csv(path, encoding='latin1')
|
| 675 |
+
p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 676 |
+
|
| 677 |
+
if p_col:
|
| 678 |
+
# تحويل السعر وتطبيق دالة التنظيف (IQR) التي عملناها في الخطوة السابقة
|
| 679 |
+
df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', ''), errors='coerce')
|
| 680 |
+
df_temp[p_col] = df_temp[p_col].fillna(df_temp[p_col].mean())
|
| 681 |
+
|
| 682 |
+
# تطبيق دالة معالجة القيم المتطرفة (نفس الدالة السابقة)
|
| 683 |
+
Q1 = df_temp[p_col].quantile(0.25)
|
| 684 |
+
Q3 = df_temp[p_col].quantile(0.75)
|
| 685 |
+
IQR = Q3 - Q1
|
| 686 |
+
lower = Q1 - 1.5 * IQR
|
| 687 |
+
upper = Q3 + 1.5 * IQR
|
| 688 |
+
|
| 689 |
+
# استبدال القيم بالمتوسط
|
| 690 |
+
df_temp.loc[(df_temp[p_col] < lower) | (df_temp[p_col] > upper), p_col] = df_temp[p_col].mean()
|
| 691 |
+
|
| 692 |
+
cleaned_plot_data[label] = df_temp[p_col] / 22 # التحويل للدولار
|
| 693 |
+
except:
|
| 694 |
+
continue
|
| 695 |
+
|
| 696 |
+
# 2. رسم الصندوق النهائي للتأكد من نظافة البيانات
|
| 697 |
+
if cleaned_plot_data:
|
| 698 |
+
plt.figure(figsize=(14, 5))
|
| 699 |
+
|
| 700 |
+
# دمج البيانات في DataFrame واحد للرسم
|
| 701 |
+
df_final = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in cleaned_plot_data.items()]))
|
| 702 |
+
|
| 703 |
+
# رسم الصناديق
|
| 704 |
+
df_final.boxplot()
|
| 705 |
+
|
| 706 |
+
plt.title("Price Distribution AFTER Cleaning Outliers (Verification)", fontsize=14)
|
| 707 |
+
plt.ylabel("Price in USD ($)")
|
| 708 |
+
plt.grid(axis='y', linestyle='--', alpha=0.7)
|
| 709 |
+
|
| 710 |
+
plt.show()
|
| 711 |
+
else:
|
| 712 |
+
print("No data available to plot. Check your files!")
|
| 713 |
+
|
| 714 |
+
import pandas as pd
|
| 715 |
+
import os
|
| 716 |
+
|
| 717 |
+
# المسار لملف المعالجات (يمكنك تغييره لـ GPU.csv أو أي ملف آخر)
|
| 718 |
+
file_path = 'CPU.csv'
|
| 719 |
+
|
| 720 |
+
if os.path.exists(file_path):
|
| 721 |
+
try:
|
| 722 |
+
# 1. قراءة الملف مع معالجة التشفير (latin1) لضمان عدم ظهور أخطاء
|
| 723 |
+
df = pd.read_csv(file_path, encoding='latin1')
|
| 724 |
+
|
| 725 |
+
print(f"--- Showing first 5 records of {file_path} ---")
|
| 726 |
+
|
| 727 |
+
# 2. تنفيذ أمر head(5) لعرض أول 5 أسطر
|
| 728 |
+
# سيظهر لك أسماء القطع، المقابس (Sockets)، والأسعار (Price)
|
| 729 |
+
display(df.head(5))
|
| 730 |
+
|
| 731 |
+
except Exception as e:
|
| 732 |
+
print(f"Error reading the file: {e}")
|
| 733 |
+
else:
|
| 734 |
+
print(f"File '{file_path}' not found. Please upload it to the sidebar.")
|
| 735 |
+
|
| 736 |
+
import pandas as pd
|
| 737 |
+
import seaborn as sns
|
| 738 |
+
import matplotlib.pyplot as plt
|
| 739 |
+
import os
|
| 740 |
+
|
| 741 |
+
# 1. تحميل ملف المعالجات كمثال
|
| 742 |
+
file_path = 'CPU.csv'
|
| 743 |
+
|
| 744 |
+
if os.path.exists(file_path):
|
| 745 |
+
try:
|
| 746 |
+
# قراءة البيانات بتشفير latin1
|
| 747 |
+
df_cpu = pd.read_csv(file_path, encoding='latin1')
|
| 748 |
+
|
| 749 |
+
# تنظيف عمود السعر (المتغير Y)
|
| 750 |
+
p_col = next((c for c in df_cpu.columns if 'price' in c.lower() or 'mrp' in c.lower()), None)
|
| 751 |
+
|
| 752 |
+
if p_col:
|
| 753 |
+
# تحويل السعر لرقم وتنظيفه
|
| 754 |
+
df_cpu['Price_Clean'] = pd.to_numeric(df_cpu[p_col].astype(str).str.replace(',', '').str.replace('$', ''), errors='coerce')
|
| 755 |
+
|
| 756 |
+
# المتغير الثاني (X): سنستخدم "ترتيب القطعة" كمؤشر افتراضي
|
| 757 |
+
df_cpu['Item_Rank'] = range(len(df_cpu))
|
| 758 |
+
|
| 759 |
+
# حذف القيم الفارغة لضمان دقة خط الانحدار
|
| 760 |
+
df_plot = df_cpu[['Item_Rank', 'Price_Clean']].dropna()
|
| 761 |
+
|
| 762 |
+
# 2. رسم النقاط مع خط الانحدار (Regplot)
|
| 763 |
+
plt.figure(figsize=(12, 6))
|
| 764 |
+
|
| 765 |
+
# رسم العلاقة: x هو الترتيب، y هو السعر
|
| 766 |
+
# الخط الأحمر يمثل "الاتجاه العام" للأسعار
|
| 767 |
+
sns.regplot(data=df_plot, x='Item_Rank', y='Price_Clean',
|
| 768 |
+
scatter_kws={'s': 80, 'alpha': 0.5, 'color': 'royalblue'},
|
| 769 |
+
line_kws={'color': 'red', 'lw': 2})
|
| 770 |
+
|
| 771 |
+
# إضافة العنوان والمحاور بالإنجليزية
|
| 772 |
+
plt.title('Price Trend Analysis (Regression Plot)', fontsize=15)
|
| 773 |
+
plt.xlabel('Item Sequence / Rank', fontsize=12)
|
| 774 |
+
plt.ylabel('Price in USD ($)', fontsize=12)
|
| 775 |
+
|
| 776 |
+
plt.grid(True, linestyle='--', alpha=0.6)
|
| 777 |
+
plt.show()
|
| 778 |
+
|
| 779 |
+
else:
|
| 780 |
+
print("Price column not found in the CSV!")
|
| 781 |
+
except Exception as e:
|
| 782 |
+
print(f"Error: {e}")
|
| 783 |
+
else:
|
| 784 |
+
print("File CPU.csv not found! Please upload it.")
|
| 785 |
+
|