teoo33 commited on
Commit
f62816d
·
verified ·
1 Parent(s): ad1961b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +260 -0
app.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from openai import OpenAI
4
+ import json
5
+ import os
6
+
7
+ # تنظیم API کلاینت با متغیر محیطی
8
+ api_key = os.getenv("OPENAI_API_KEY")
9
+ if not api_key:
10
+ raise ValueError("OPENAI_API_KEY در متغیرهای محیطی تنظیم نشده است.")
11
+ client = OpenAI(api_key=api_key)
12
+
13
+ # متغیرهای سراسری
14
+ iteration_count = 0
15
+ iteration_history = ""
16
+ prompt_output = ""
17
+ knowledge_base_output = ""
18
+ faq_output = ""
19
+ business_info = None
20
+ product_info = None
21
+
22
+ # پرامپت مادر با جزئیات کامل
23
+ mother_prompt = """
24
+ You are the Nova System, an innovative problem-solving approach implemented by a dynamic consortium of virtual experts, each serving a distinct role. Your goal is to assist the user in generating high-quality prompts, a comprehensive knowledge base, and an automatically generated Frequently Asked Questions (FAQ) section for chatbots.
25
+
26
+ **Nova System Process:**
27
+ The Nova System process is iterative and cyclical, involving the following key stages:
28
+ 1. **Receiving and Processing User Information Forms:** Process the information from the Business Information Form and Product/Service Information Form provided by the user.
29
+ 2. **Assigning Expert Roles:**
30
+ - **Discussion Continuity Expert (DCE):** Manage and guide the process, provide instructions, summarize progress, and define goals for each iteration.
31
+ - **Prompt Engineering Expert (PEE):** Generate initial drafts of:
32
+ - Chatbot prompt in English with sections: Persona, Tone, Guidelines, About Us, Responses to Common Questions, Contact Information, Additional Guidelines. Tone must be friendly, casual, concise (under 100 words per response unless necessary), and use loving emojis.
33
+ - Knowledge base in JSON-like format with fields: name, description, variants (size and price), objectID.
34
+ - FAQ in JSON-like format with categories, topics, questions, and short, friendly answers.
35
+ - **Critical Analysis Expert (CAE):** Review and critique outputs, ensuring they match the desired tone, structure, and detail level, providing improvement suggestions.
36
+ 3. **Iterations and Expert Dialogue:** Conduct iterations with the following steps in Persian (Farsi):
37
+ - **DCE's Instructions:** Provide instructions for PEE and CAE.
38
+ - **PEE Output:** Generate or refine chatbot prompt, knowledge base, and FAQ.
39
+ - **CAE Analysis:** Critique PEE outputs and suggest improvements.
40
+ - **DCE Summary:** Summarize progress and set goals for the next iteration.
41
+ 4. **Iterate the Process:** Continue until high-quality outputs are achieved.
42
+ 5. **Present the Final Outputs:**
43
+ - Final prompt in English with specified sections.
44
+ - Knowledge base in JSON-like format.
45
+ - FAQ in JSON-like format.
46
+ - Separate each section with exactly "---" (three dashes) and nothing else. **Do not add any extra text before, after, or between sections (e.g., no "Here is the output", no headings like "### Prompt:", no explanations).**
47
+
48
+ Conduct all dialogues in Persian, but output the final prompt in English and knowledge base/FAQ in JSON-like format. Ensure the tone is friendly, casual, and uses loving emojis where appropriate.
49
+ """
50
+
51
+ # تابع برای تبدیل داده‌ها به فرمت JSON-serializable
52
+ def convert_to_serializable(obj):
53
+ if isinstance(obj, pd.Timestamp):
54
+ return obj.isoformat()
55
+ elif isinstance(obj, list):
56
+ return [convert_to_serializable(item) for item in obj]
57
+ elif isinstance(obj, dict):
58
+ return {key: convert_to_serializable(value) for key, value in obj.items()}
59
+ return obj
60
+
61
+ # تابع برای اعتبارسنجی و اصلاح خروجی
62
+ def validate_and_fix_output(output):
63
+ print("خروجی خام مدل:", output) # چاپ خروجی خام برای دیباگ
64
+ parts = output.split("---")
65
+ parts = [part.strip() for part in parts if part.strip()] # حذف بخش‌های خالی
66
+ print("بخش‌های جدا شده:", parts) # چاپ بخش‌ها برای دیباگ
67
+
68
+ # اگه متن اضافی قبل از اولین --- بود، اون رو نادیده بگیر
69
+ if len(parts) > 3 and not parts[0].startswith("**Persona:") and not parts[0].startswith("["):
70
+ parts = parts[1:] # متن اضافی رو حذف کن و از بخش بعدی شروع کن
71
+
72
+ # تخصیص بخش‌ها بر اساس ترتیب
73
+ prompt_part = parts[0] if len(parts) > 0 else "پرامپت تولید نشد 😔"
74
+ kb_part = parts[1] if len(parts) > 1 else "پایگاه دانش تولید نشد 😕"
75
+ faq_part = parts[2] if len(parts) > 2 else "FAQ تولید نشد 🥳"
76
+
77
+ return [prompt_part, kb_part, faq_part]
78
+
79
+ # تابع برای خوندن و پردازش فایل‌های اکسل
80
+ def process_excel_files(file1, file2):
81
+ global business_info, product_info
82
+ business_info = pd.read_excel(file1.name).to_dict(orient="records")[0]
83
+ product_info = pd.read_excel(file2.name).to_dict(orient="records")
84
+ return business_info, product_info
85
+
86
+ # تابع شروع فرایند
87
+ def start_process(file1, file2):
88
+ global iteration_count, iteration_history, business_info, product_info
89
+ iteration_count = 1
90
+ iteration_history = "سلام عزیزم! من سیستم نوا هستم، یه دستیار باحال برای ساخت پرامپت، پایگاه دانش و FAQ 😍 فرایند شروع شد!\n"
91
+
92
+ # پردازش فایل‌ها
93
+ business_info, product_info = process_excel_files(file1, file2)
94
+ business_info_serializable = convert_to_serializable(business_info)
95
+ product_info_serializable = convert_to_serializable(product_info)
96
+
97
+ # دستورات DCE
98
+ dce_instructions = f"iteration {iteration_count}: لطفاً یه پرامپت به انگلیسی (با بخش‌های Persona, Tone, Guidelines, About Us و غیره)، پایگاه دانش به فرمت JSON (با name, description, variants, objectID) و FAQ به فرمت JSON (با دسته‌بندی و جواب‌های کوتاه و دوستانه) بسازید."
99
+ iteration_history += f"**دستورات DCE:** {dce_instructions}\n"
100
+
101
+ # تولید توسط PEE
102
+ pee_prompt = f"""
103
+ {mother_prompt}
104
+ شما Prompt Engineering Expert (PEE) هستید. بر اساس اطلاعات زیر، پرامپت، پایگاه دانش و FAQ رو بسازید:
105
+ اطلاعات کسب‌وکار: {json.dumps(business_info_serializable, ensure_ascii=False)}
106
+ اطلاعات محصولات: {json.dumps(product_info_serializable, ensure_ascii=False)}
107
+ {dce_instructions}
108
+ خروجی رو با --- جدا کنید.
109
+ """
110
+ pee_response = client.chat.completions.create(
111
+ model="gpt-4o",
112
+ messages=[{"role": "system", "content": pee_prompt}]
113
+ )
114
+ pee_output = pee_response.choices[0].message.content
115
+ iteration_history += f"**خروجی PEE:**\n{pee_output}\n"
116
+
117
+ # نقد توسط CAE
118
+ cae_prompt = f"""
119
+ {mother_prompt}
120
+ شما Critical Analysis Expert (CAE) هستید. خروجی PEE رو نقد کنید، مطمئن شید لحن دوستانه‌ست، ساختار JSON درسته و جزئیات کافی داره:
121
+ خروجی PEE:\n{pee_output}
122
+ """
123
+ cae_response = client.chat.completions.create(
124
+ model="gpt-4o",
125
+ messages=[{"role": "system", "content": cae_prompt}]
126
+ )
127
+ cae_output = cae_response.choices[0].message.content
128
+ iteration_history += f"**نقد CAE:**\n{cae_output}\n"
129
+
130
+ # جمع‌بندی DCE
131
+ dce_summary = f"""
132
+ **جمع‌بندی DCE:** iteration {iteration_count} تموم شد 🌟
133
+ **وضعیت فعلی:** پرامپت، پایگاه دانش و FAQ اولیه ساخته شدن.
134
+ **اهداف بعدی:**
135
+ #G-{iteration_count}-1: بهبود لحن و جزئیات بر اساس نقد CAE.
136
+ #G-{iteration_count}-2: تکمیل فرمت JSON.
137
+ **پایان iteration {iteration_count}**
138
+ """
139
+ iteration_history += dce_summary
140
+
141
+ return iteration_history, "", "", ""
142
+
143
+ # تابع ادامه Iteration
144
+ def continue_iteration():
145
+ global iteration_count, iteration_history
146
+ iteration_count += 1
147
+
148
+ business_info_serializable = convert_to_serializable(business_info)
149
+ product_info_serializable = convert_to_serializable(product_info)
150
+
151
+ # دستورات DCE
152
+ dce_instructions = f"iteration {iteration_count}: لطفاً خروجی قبلی رو بر اساس نقد CAE بهبود بدید، لحن رو دوستانه‌تر کنید و فرمت JSON رو دقیق‌تر کنید."
153
+ iteration_history += f"**دستورات DCE:** {dce_instructions}\n"
154
+
155
+ # تولید توسط PEE
156
+ pee_prompt = f"""
157
+ {mother_prompt}
158
+ شما Prompt Engineering Expert (PEE) هستید. خروجی قبلی رو بر اساس نقد CAE بهبود بدید:
159
+ اطلاعات کسب‌وکار: {json.dumps(business_info_serializable, ensure_ascii=False)}
160
+ اطلاعات محصولات: {json.dumps(product_info_serializable, ensure_ascii=False)}
161
+ تاریخچه iteration قبلی:\n{iteration_history}
162
+ {dce_instructions}
163
+ خروجی رو با --- جدا کنید.
164
+ """
165
+ pee_response = client.chat.completions.create(
166
+ model="gpt-4o",
167
+ messages=[{"role": "system", "content": pee_prompt}]
168
+ )
169
+ pee_output = pee_response.choices[0].message.content
170
+ iteration_history += f"**خروجی PEE:**\n{pee_output}\n"
171
+
172
+ # نقد توسط CAE
173
+ cae_prompt = f"""
174
+ {mother_prompt}
175
+ شما Critical Analysis Expert (CAE) هستید. خروجی جدید PEE رو نقد کنید و مطمئن شید لحن دوستانه‌ست و فرمت JSON درسته:
176
+ خروجی PEE:\n{pee_output}
177
+ """
178
+ cae_response = client.chat.completions.create(
179
+ model="gpt-4o",
180
+ messages=[{"role": "system", "content": cae_prompt}]
181
+ )
182
+ cae_output = cae_response.choices[0].message.content
183
+ iteration_history += f"**نقد CAE:**\n{cae_output}\n"
184
+
185
+ # جمع‌بندی DCE
186
+ dce_summary = f"""
187
+ **جمع‌بندی DCE:** iteration {iteration_count} تموم شد 😊
188
+ **وضعیت فعلی:** خروجی‌ها بهبود یافتن.
189
+ **اهداف بعدی:**
190
+ #G-{iteration_count}-1: ادامه بهبود یا اتمام فرایند.
191
+ **پایان iteration {iteration_count}**
192
+ """
193
+ iteration_history += dce_summary
194
+
195
+ return iteration_history, "", "", ""
196
+
197
+ # تابع پایان و تولید خروجی نهایی
198
+ def end_process():
199
+ global iteration_history, prompt_output, knowledge_base_output, faq_output
200
+
201
+ business_info_serializable = convert_to_serializable(business_info)
202
+ product_info_serializable = convert_to_serializable(product_info)
203
+
204
+ # تولید خروجی نهایی
205
+ final_prompt = f"""
206
+ {mother_prompt}
207
+ فرایند iteration‌ها تموم شده. لطفاً خروجی نهایی رو به این ترتیب تولید کنید:
208
+ 1. پرامپت چت‌بات به انگلیسی با بخش‌های:
209
+ - Persona
210
+ - Tone
211
+ - Guidelines
212
+ - About Us
213
+ - Responses to Common Questions
214
+ - Contact Information
215
+ - Additional Guidelines
216
+ لحن باید دوستانه، عامیانه، کوتاه (زیر 100 کلمه) و با ایموجی‌های جذاب باشه.
217
+ ---
218
+ 2. پایگاه دانش به فرمت JSON-like با فیلدهای: name, description, variants (شامل size و price), objectID. برای هر محصول یا خدمت یه ورودی جدا بساز.
219
+ ---
220
+ 3. FAQ به فرمت JSON-like با دسته‌بندی‌ها (مثل Services, Care)، موضوعات، سوالات و جواب‌های کوتاه و دوستانه.
221
+ اطلاعات کسب‌وکار: {json.dumps(business_info_serializable, ensure_ascii=False)}
222
+ اطلاعات محصولات: {json.dumps(product_info_serializable, ensure_ascii=False)}
223
+ تاریخچه iteration‌ها:\n{iteration_history}
224
+ **هر بخش رو با دقیقاً "---" جدا کن. هیچ متن اضافی قبل، بعد یا بین بخش‌ها نذار (مثل "Here is the output" یا تیترهایی مثل "### Prompt:"). اگه هر بخش تولید نشد، به جاش یه نمونه حداقلی بساز.**
225
+ """
226
+ final_response = client.chat.completions.create(
227
+ model="gpt-4o",
228
+ messages=[{"role": "system", "content": final_prompt}]
229
+ )
230
+ final_output = final_response.choices[0].message.content
231
+ print("خروجی خام نهایی:", final_output) # چاپ خروجی خام برای دیباگ
232
+
233
+ # اعتبارسنجی و جداسازی خروجی‌ها
234
+ parts = validate_and_fix_output(final_output)
235
+ prompt_output = parts[0]
236
+ knowledge_base_output = parts[1]
237
+ faq_output = parts[2]
238
+
239
+ iteration_history += "\n**فرایند تموم شد و خروجی نهایی آماده‌ست! 🎉**\n"
240
+ return iteration_history, prompt_output, knowledge_base_output, faq_output
241
+
242
+ # رابط کاربری Gradio
243
+ with gr.Blocks() as demo:
244
+ gr.Markdown("# سیستم نوا 🌟")
245
+ with gr.Row():
246
+ file1 = gr.File(label="فرم اطلاعات اولیه وردست")
247
+ file2 = gr.File(label="فرم اطلاعات محصولات/خدمات")
248
+ start_btn = gr.Button("شروع")
249
+ iteration_box = gr.Textbox(label="تاریخچه Iteration", lines=10)
250
+ continue_btn = gr.Button("ادامه دهید")
251
+ end_btn = gr.Button("پایان")
252
+ prompt_box = gr.Textbox(label="پرامپت نهایی (انگلیسی)")
253
+ kb_box = gr.Textbox(label="پایگاه دانش (JSON)")
254
+ faq_box = gr.Textbox(label="پرسش و پاسخ‌ها (JSON)")
255
+
256
+ start_btn.click(start_process, inputs=[file1, file2], outputs=[iteration_box, prompt_box, kb_box, faq_box])
257
+ continue_btn.click(continue_iteration, inputs=[], outputs=[iteration_box, prompt_box, kb_box, faq_box])
258
+ end_btn.click(end_process, inputs=[], outputs=[iteration_box, prompt_box, kb_box, faq_box])
259
+
260
+ demo.launch()