File size: 14,774 Bytes
977eefa
 
 
7b97d88
 
977eefa
 
7b97d88
 
4d05878
7b97d88
4d05878
7b97d88
 
 
 
4d05878
977eefa
7b97d88
977eefa
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
977eefa
 
 
7b97d88
4d05878
7b97d88
4d05878
7b97d88
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
 
 
 
 
 
 
 
 
 
 
 
7b97d88
4d05878
7b97d88
 
 
 
 
4d05878
7b97d88
 
 
 
 
 
 
4d05878
7b97d88
 
4d05878
7b97d88
4d05878
 
 
 
 
 
 
7b97d88
 
 
 
 
 
 
 
 
 
4d05878
 
7b97d88
 
4d05878
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
4d05878
7b97d88
4d05878
 
 
 
 
 
 
7b97d88
 
 
 
4d05878
 
 
 
 
 
7b97d88
 
4d05878
 
 
 
 
 
7b97d88
 
4d05878
 
 
 
 
 
7b97d88
 
 
 
977eefa
7b97d88
4d05878
 
 
 
7b97d88
 
4d05878
 
 
 
7b97d88
 
 
 
 
 
4d05878
 
 
 
 
 
 
7b97d88
 
 
 
4d05878
 
7b97d88
 
 
 
4d05878
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
 
 
 
 
 
 
 
 
4d05878
 
 
 
 
 
7b97d88
 
4d05878
7b97d88
4d05878
7b97d88
4d05878
 
 
 
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
977eefa
7b97d88
977eefa
4d05878
 
 
7b97d88
977eefa
4d05878
 
 
7b97d88
977eefa
 
7b97d88
977eefa
4d05878
 
 
 
7b97d88
977eefa
4d05878
 
 
7b97d88
 
 
977eefa
7b97d88
977eefa
7b97d88
 
 
 
4d05878
 
 
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
 
 
 
 
4d05878
 
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
 
 
 
 
 
 
 
4d05878
7b97d88
 
 
4d05878
7b97d88
 
 
 
 
 
977eefa
7b97d88
 
 
 
4d05878
7b97d88
 
 
4d05878
7b97d88
 
 
 
 
 
 
 
4d05878
977eefa
4d05878
977eefa
7b97d88
 
 
 
 
4d05878
7b97d88
4d05878
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
977eefa
7b97d88
 
4d05878
 
7b97d88
 
977eefa
4d05878
977eefa
7b97d88
 
 
 
 
4d05878
7b97d88
4d05878
7b97d88
4d05878
 
 
 
7b97d88
4d05878
 
 
 
7b97d88
 
4d05878
7b97d88
 
 
 
4d05878
 
7b97d88
 
 
 
 
977eefa
 
7b97d88
4d05878
 
7b97d88
 
977eefa
7b97d88
 
 
 
 
 
 
 
 
 
4d05878
 
7b97d88
977eefa
 
 
7b97d88
 
 
 
 
 
4d05878
7b97d88
4d05878
7b97d88
977eefa
7b97d88
 
 
 
 
 
977eefa
4d05878
 
 
 
7b97d88
4d05878
 
7b97d88
 
4d05878
 
 
 
 
 
7b97d88
 
4d05878
977eefa
 
7b97d88
4d05878
7b97d88
 
4d05878
7b97d88
977eefa
7b97d88
977eefa
 
7b97d88
977eefa
7b97d88
4d05878
977eefa
7b97d88
4d05878
 
 
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d05878
7b97d88
 
 
 
 
4d05878
 
7b97d88
 
 
 
 
 
 
 
 
4d05878
977eefa
7b97d88
4d05878
 
 
7b97d88
977eefa
7b97d88
977eefa
7b97d88
 
 
 
 
 
 
977eefa
7b97d88
977eefa
7b97d88
 
 
 
 
 
977eefa
7b97d88
 
 
 
 
 
4d05878
 
7b97d88
977eefa
7b97d88
 
 
 
 
 
 
 
 
 
 
 
 
977eefa
7b97d88
4d05878
977eefa
7b97d88
 
 
 
 
 
977eefa
7b97d88
4d05878
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b97d88
 
 
 
 
 
4d05878
7b97d88
 
977eefa
 
7b97d88
4d05878
 
 
7b97d88
977eefa
7b97d88
977eefa
7b97d88
977eefa
7b97d88
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
import gradio as gr
import sqlite3
import hashlib
import html
import re
from datetime import datetime, timedelta

DB_NAME = "testimonials.db"

# ==================================================
# Database
# ==================================================

def get_connection():
    return sqlite3.connect(DB_NAME, check_same_thread=False)


def init_db():
    conn = get_connection()
    c = conn.cursor()

    c.execute("""
    CREATE TABLE IF NOT EXISTS testimonials (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        role TEXT,
        content TEXT NOT NULL,
        sentiment TEXT,
        rating INTEGER DEFAULT 5,
        timestamp TEXT NOT NULL,
        likes INTEGER DEFAULT 0,
        is_highlighted INTEGER DEFAULT 0,
        ip_hash TEXT
    )
    """)

    conn.commit()
    conn.close()


# ==================================================
# Utilities
# ==================================================

def clean_text(text):
    if not text:
        return ""

    text = text.strip()
    text = re.sub(r"\s+", " ", text)

    return text


def contains_bad_words(text):

    bad_words = [
        "يلعن",
        "تبن",
        "سافل",
        "كلب",
        "خنزير",
        "عاهرة"
    ]

    normalized = re.sub(r"\s+", "", text.lower())

    return any(word in normalized for word in bad_words)


def escape_safe(text):
    return html.escape(text)


def get_ip_hash(request: gr.Request):

    try:
        client_ip = request.client.host
        return hashlib.sha256(
            client_ip.encode()
        ).hexdigest()[:16]

    except:
        return "unknown"


def detect_sentiment(text):

    positive_words = [
        "رائع",
        "ممتاز",
        "جميل",
        "احترافي",
        "مفيد",
        "مذهل"
    ]

    negative_words = [
        "سيء",
        "ضعيف",
        "فاشل",
        "سيئة"
    ]

    text = text.lower()

    positive_score = sum(
        word in text for word in positive_words
    )

    negative_score = sum(
        word in text for word in negative_words
    )

    if positive_score > negative_score:
        return "إيجابي 😊"

    elif negative_score > positive_score:
        return "سلبي 😕"

    return "محايد 😐"


def format_time(timestamp):

    try:
        dt = datetime.fromisoformat(timestamp)

        now = datetime.now()

        diff = now - dt

        if diff.days > 7:
            return dt.strftime("%Y/%m/%d")

        elif diff.days > 0:
            return f"منذ {diff.days} يوم"

        elif diff.seconds >= 3600:
            hours = diff.seconds // 3600
            return f"منذ {hours} ساعة"

        elif diff.seconds >= 60:
            minutes = diff.seconds // 60
            return f"منذ {minutes} دقيقة"

        return "الآن"

    except:
        return "غير معروف"


# ==================================================
# Add Testimonial
# ==================================================

def add_testimonial(
    name,
    role,
    content,
    rating,
    request: gr.Request
):

    content = clean_text(content)

    if not content:
        return (
            "❌ الرجاء كتابة رأيك",
            "",
            "",
            update_display()
        )

    if len(content) > 800:
        return (
            "❌ الحد الأقصى 800 حرف",
            "",
            "",
            update_display()
        )

    if contains_bad_words(content):
        return (
            "❌ يوجد كلمات غير مناسبة",
            "",
            "",
            update_display()
        )

    ip_hash = get_ip_hash(request)

    conn = get_connection()
    c = conn.cursor()

    # Anti spam
    one_hour_ago = (
        datetime.now() - timedelta(hours=1)
    ).isoformat()

    c.execute("""
    SELECT COUNT(*)
    FROM testimonials
    WHERE ip_hash = ?
    AND timestamp >= ?
    """, (ip_hash, one_hour_ago))

    count = c.fetchone()[0]

    if count >= 3:
        conn.close()

        return (
            "❌ وصلت الحد المسموح حالياً",
            "",
            "",
            update_display()
        )

    name = clean_text(name)
    role = clean_text(role)

    if not name:
        name = "مجهول"

    sentiment = detect_sentiment(content)

    c.execute("""
    INSERT INTO testimonials (
        name,
        role,
        content,
        sentiment,
        rating,
        timestamp,
        likes,
        is_highlighted,
        ip_hash
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, (
        name,
        role,
        content,
        sentiment,
        int(rating),
        datetime.now().isoformat(),
        0,
        0,
        ip_hash
    ))

    conn.commit()
    conn.close()

    return (
        "✅ تم نشر رأيك بنجاح",
        "",
        "",
        update_display()
    )


# ==================================================
# Fetch Testimonials
# ==================================================

def get_testimonials(
    filter_type="all",
    sort_by="newest"
):

    conn = get_connection()
    c = conn.cursor()

    query = """
    SELECT
        id,
        name,
        role,
        content,
        sentiment,
        rating,
        timestamp,
        likes,
        is_highlighted
    FROM testimonials
    """

    conditions = []

    if filter_type == "highlight":
        conditions.append(
            "is_highlighted = 1"
        )

    elif filter_type == "liked":
        conditions.append(
            "likes > 0"
        )

    if conditions:
        query += " WHERE " + " AND ".join(conditions)

    if sort_by == "likes":
        query += """
        ORDER BY likes DESC,
        timestamp DESC
        """

    else:
        query += """
        ORDER BY timestamp DESC
        """

    c.execute(query)

    rows = c.fetchall()

    conn.close()

    return rows


# ==================================================
# Render Card
# ==================================================

def render_card(row):

    (
        testimonial_id,
        name,
        role,
        content,
        sentiment,
        rating,
        timestamp,
        likes,
        is_highlighted
    ) = row

    name = escape_safe(name)
    role = escape_safe(role)
    content = escape_safe(content)

    stars = "⭐" * int(rating)

    highlight_style = ""

    if is_highlighted:
        highlight_style = """
        border-right:5px solid #f59e0b;
        background:#fffbeb;
        """

    role_html = ""

    if role:
        role_html = f"""
        <span style="
            background:#eef2ff;
            color:#4338ca;
            padding:0.25rem 0.7rem;
            border-radius:999px;
            font-size:0.75rem;
        ">
            {role}
        </span>
        """

    return f"""
    <div style="
        background:white;
        border-radius:24px;
        padding:1.5rem;
        margin-bottom:1rem;
        border:1px solid #e2e8f0;
        box-shadow:0 4px 12px rgba(0,0,0,0.05);
        {highlight_style}
    ">

        <div style="
            display:flex;
            justify-content:space-between;
            align-items:center;
            flex-wrap:wrap;
            gap:1rem;
        ">

            <div>

                <div style="
                    font-size:1rem;
                    font-weight:700;
                    color:#0f172a;
                ">
                    {name}
                </div>

                <div style="
                    display:flex;
                    gap:0.5rem;
                    margin-top:0.5rem;
                    align-items:center;
                    flex-wrap:wrap;
                ">

                    {role_html}

                    <span style="
                        color:#64748b;
                        font-size:0.8rem;
                    ">
                        {sentiment}
                    </span>

                </div>

            </div>

            <div style="
                color:#94a3b8;
                font-size:0.75rem;
            ">
                {format_time(timestamp)}
            </div>

        </div>

        <div style="
            margin-top:1rem;
            color:#1e293b;
            line-height:1.8;
        ">
            {content}
        </div>

        <div style="
            margin-top:1rem;
            display:flex;
            justify-content:space-between;
            align-items:center;
        ">

            <div>
                {stars}
            </div>

            <div style="
                color:#64748b;
                font-size:0.9rem;
            ">
                👍 {likes}
            </div>

        </div>

    </div>
    """


# ==================================================
# Update Display
# ==================================================

def update_display(
    filter_type="all",
    sort_by="newest"
):

    rows = get_testimonials(
        filter_type,
        sort_by
    )

    if not rows:

        return """
        <div style="
            background:white;
            border-radius:24px;
            padding:2rem;
            text-align:center;
            border:1px dashed #cbd5e1;
            color:#64748b;
        ">
            ✨ لا توجد آراء حالياً
        </div>
        """

    average_rating = round(
        sum(row[5] for row in rows)
        / len(rows),
        1
    )

    html_output = f"""
    <div style="
        margin-bottom:1rem;
        background:#e0e7ff;
        padding:0.8rem 1rem;
        border-radius:999px;
        display:inline-block;
        font-weight:600;
        color:#3730a3;
    ">
        📊 عدد الآراء: {len(rows)}
        |
        ⭐ متوسط التقييم: {average_rating}
    </div>
    """

    for row in rows:
        html_output += render_card(row)

    return html_output


# ==================================================
# Interface
# ==================================================

def create_interface():

    with gr.Blocks(
        title="جدار الشفافية",
        theme=gr.themes.Soft()
    ) as demo:

        gr.HTML("""
        <div style="
            text-align:center;
            margin-bottom:2rem;
        ">

            <h1 style="
                font-size:2.7rem;
                font-weight:800;
                margin-bottom:0.5rem;
                background:
                linear-gradient(
                    135deg,
                    #1e293b,
                    #4338ca
                );
                -webkit-background-clip:text;
                color:transparent;
            ">
                جدار الشفافية
            </h1>

            <p style="
                color:#475569;
                font-size:1rem;
            ">
                منصة آراء مباشرة وشفافة
            </p>

        </div>
        """)

        with gr.Row():

            # Left
            with gr.Column(scale=1):

                gr.Markdown(
                    "## 📝 أضف رأيك"
                )

                name_input = gr.Textbox(
                    label="الاسم",
                    placeholder="اختياري"
                )

                role_input = gr.Textbox(
                    label="الدور",
                    placeholder="مثال: مهندس"
                )

                rating_input = gr.Slider(
                    minimum=1,
                    maximum=5,
                    value=5,
                    step=1,
                    label="التقييم"
                )

                content_input = gr.Textbox(
                    label="الرأي",
                    placeholder="شارك رأيك هنا...",
                    lines=5
                )

                submit_btn = gr.Button(
                    "📢 نشر الرأي",
                    variant="primary"
                )

                status_output = gr.Markdown()

            # Right
            with gr.Column(scale=2):

                gr.Markdown(
                    "## 💬 آراء المستخدمين"
                )

                with gr.Row():

                    filter_dropdown = gr.Dropdown(
                        choices=[
                            ("الكل", "all"),
                            ("المؤثرة", "highlight"),
                            ("الأكثر إعجاباً", "liked")
                        ],
                        value="all",
                        label="فلترة"
                    )

                    sort_dropdown = gr.Dropdown(
                        choices=[
                            ("الأحدث", "newest"),
                            ("الأكثر إعجاباً", "likes")
                        ],
                        value="newest",
                        label="ترتيب"
                    )

                refresh_btn = gr.Button(
                    "🔄 تحديث",
                    variant="secondary"
                )

                testimonials_display = gr.HTML()

        # Submit
        submit_btn.click(
            fn=add_testimonial,
            inputs=[
                name_input,
                role_input,
                content_input,
                rating_input
            ],
            outputs=[
                status_output,
                name_input,
                role_input,
                testimonials_display
            ]
        )

        # Refresh button
        refresh_btn.click(
            fn=update_display,
            inputs=[
                filter_dropdown,
                sort_dropdown
            ],
            outputs=testimonials_display
        )

        # Filter change
        filter_dropdown.change(
            fn=update_display,
            inputs=[
                filter_dropdown,
                sort_dropdown
            ],
            outputs=testimonials_display
        )

        # Sort change
        sort_dropdown.change(
            fn=update_display,
            inputs=[
                filter_dropdown,
                sort_dropdown
            ],
            outputs=testimonials_display
        )

        # Initial load
        demo.load(
            fn=update_display,
            inputs=[
                filter_dropdown,
                sort_dropdown
            ],
            outputs=testimonials_display
        )

    return demo


# ==================================================
# Run App
# ==================================================

if __name__ == "__main__":

    init_db()

    demo = create_interface()

    demo.launch()