MohammadJMH commited on
Commit
da1a5fa
·
verified ·
1 Parent(s): e17edd9

Delete app.py

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