edwinbh commited on
Commit
aece41c
·
verified ·
1 Parent(s): e5c52b4

Upload gradio_chat_interface.py

Browse files
Files changed (1) hide show
  1. gradio_chat_interface.py +167 -0
gradio_chat_interface.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ from datetime import datetime
5
+
6
+ # URL webhook شما
7
+ WEBHOOK_URL = "http://130.185.121.155:5678/webhook/voice-agent"
8
+
9
+ # ذخیره session_id برای هر کاربر
10
+ session_data = {}
11
+
12
+ def send_message(phone_number, message, history):
13
+ """
14
+ ارسال پیام به webhook و دریافت پاسخ
15
+ """
16
+ if not phone_number:
17
+ return history + [("سیستم", "⚠️ لطفاً ابتدا شماره تلفن خود را وارد کنید!")]
18
+
19
+ if not message:
20
+ return history
21
+
22
+ # ساخت یا بازیابی session_id
23
+ if phone_number not in session_data:
24
+ session_data[phone_number] = f"session_{phone_number}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
25
+
26
+ session_id = session_data[phone_number]
27
+
28
+ # داده‌های ارسالی
29
+ payload = {
30
+ "user_message": message,
31
+ "context": {
32
+ "caller_phone": phone_number,
33
+ "session_id": session_id
34
+ }
35
+ }
36
+
37
+ headers = {
38
+ "Content-Type": "application/json"
39
+ }
40
+
41
+ try:
42
+ # ارسال درخواست
43
+ response = requests.post(WEBHOOK_URL, json=payload, headers=headers, timeout=30)
44
+
45
+ if response.status_code == 200:
46
+ result = response.json()
47
+ bot_response = result.get("response", "پاسخی دریافت نشد")
48
+
49
+ # اضافه کردن پیام کاربر و پاسخ ربات به تاریخچه
50
+ history.append((message, bot_response))
51
+
52
+ # نمایش اطلاعات اضافی اگر موجود باشد
53
+ if result.get("order_complete"):
54
+ history.append(("سیستم", "✅ سفارش شما کامل شد!"))
55
+
56
+ return history
57
+ else:
58
+ history.append((message, f"❌ خطا: {response.status_code} - {response.text}"))
59
+ return history
60
+
61
+ except requests.exceptions.Timeout:
62
+ history.append((message, "⏱️ زمان انتظار تمام شد. لطفاً دوباره تلاش کنید."))
63
+ return history
64
+ except requests.exceptions.RequestException as e:
65
+ history.append((message, f"❌ خطای اتصال: {str(e)}"))
66
+ return history
67
+
68
+ def clear_chat(phone_number):
69
+ """
70
+ پاک کردن تاریخچه چت
71
+ """
72
+ if phone_number in session_data:
73
+ del session_data[phone_number]
74
+ return []
75
+
76
+ # رابط Gradio
77
+ with gr.Blocks(theme=gr.themes.Soft(), css="""
78
+ .gradio-container {
79
+ max-width: 800px !important;
80
+ margin: auto !important;
81
+ }
82
+ .phone-input input {
83
+ direction: ltr !important;
84
+ text-align: left !important;
85
+ }
86
+ """) as demo:
87
+
88
+ gr.Markdown("""
89
+ # 🤖 دستیار هوشمند سفارش
90
+
91
+ به ربات سفارش‌گیری خوش آمدید! لطفاً شماره تلفن خود را وارد کرده و شروع به چت کنید.
92
+ """)
93
+
94
+ with gr.Row():
95
+ with gr.Column(scale=3):
96
+ phone_input = gr.Textbox(
97
+ label="📱 شماره تلفن",
98
+ placeholder="مثال: 09123456789",
99
+ elem_classes=["phone-input"],
100
+ interactive=True
101
+ )
102
+ with gr.Column(scale=1):
103
+ clear_btn = gr.Button("🗑️ پاک کردن چت", variant="secondary")
104
+
105
+ chatbot = gr.Chatbot(
106
+ label="گفتگو",
107
+ height=400,
108
+ type="messages",
109
+ show_label=True,
110
+ rtl=True
111
+ )
112
+
113
+ with gr.Row():
114
+ msg_input = gr.Textbox(
115
+ label="پیام شما",
116
+ placeholder="پیام خود را بنویسید...",
117
+ show_label=False,
118
+ scale=9,
119
+ submit_btn=True
120
+ )
121
+ send_btn = gr.Button("📤 ارسال", scale=1, variant="primary")
122
+
123
+ gr.Markdown("""
124
+ ### 💡 نکات:
125
+ - ابتدا شماره تلفن خود را وارد کنید
126
+ - سفارش خود را به صورت کامل بیان کنید
127
+ - می‌توانید از دستورات مختلف استفاده کنید
128
+
129
+ ### 📋 مثال‌های سفارش:
130
+ - "سلام، یک چیزبرگر دوبل و یک نوشابه می‌خوام"
131
+ - "آدرسم: تهران، خیابان ولیعصر، پلاک 123"
132
+ - "اسمم ادوین هست"
133
+ """)
134
+
135
+ # اتصال رویدادها
136
+ msg_input.submit(
137
+ fn=send_message,
138
+ inputs=[phone_input, msg_input, chatbot],
139
+ outputs=[chatbot]
140
+ ).then(
141
+ lambda: "",
142
+ outputs=[msg_input]
143
+ )
144
+
145
+ send_btn.click(
146
+ fn=send_message,
147
+ inputs=[phone_input, msg_input, chatbot],
148
+ outputs=[chatbot]
149
+ ).then(
150
+ lambda: "",
151
+ outputs=[msg_input]
152
+ )
153
+
154
+ clear_btn.click(
155
+ fn=clear_chat,
156
+ inputs=[phone_input],
157
+ outputs=[chatbot]
158
+ )
159
+
160
+ # اجرای برنامه
161
+ if __name__ == "__main__":
162
+ demo.launch(
163
+ server_name="0.0.0.0", # برای دسترسی از بیرون
164
+ server_port=7860,
165
+ share=False, # اگر می‌خواهید لینک عمومی داشته باشید، True کنید
166
+ show_error=True
167
+ )