FECUOY commited on
Commit
bab741b
·
verified ·
1 Parent(s): 9b072a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -104
app.py CHANGED
@@ -4,132 +4,123 @@ import os
4
  from utils import process_uploaded_file, export_to_docx
5
  from agents_config import create_agents
6
 
7
- def start_novel_engine(file_obj, extra_text, user_token):
8
- if not user_token:
9
- return "⚠️ يرجى إدخال التوكن الخاص بك.", None
10
-
11
- # 1. استخراج النص من الملف
12
- context = ""
13
- if file_obj is not None:
 
 
 
14
  try:
15
- context = process_uploaded_file(file_obj)
16
  except Exception as e:
17
- return f"❌ خطأ في الملف: {str(e)}", None
 
 
 
18
 
19
- full_prompt = f"{context}\n\n{extra_text}".strip()
20
- if len(full_prompt) < 10:
21
- return "⚠️ النص قصير جدًا للبدء.", None
22
 
23
  try:
24
- # 2. تشغيل الوكلاء
25
- agents = create_agents(user_token)
 
 
 
 
 
 
 
 
 
 
26
  groupchat = autogen.GroupChat(
27
- agents=[v for k, v in agents.items() if k != "editor"],
28
  messages=[],
29
- max_round=10
 
30
  )
31
- manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=agents["editor"].llm_config)
32
 
33
- # 3. التواصل مع Ling-1T
34
- chat_result = agents["editor"].initiate_chat(
35
- manager,
36
- message=f"قم بصياغة الفصل التالي وتنسيقه أدبيًا:\n\n{full_prompt}"
37
  )
 
 
 
 
38
 
39
- final_text = chat_result.chat_history[-1]['content']
40
- docx_path = export_to_docx(final_text)
41
 
42
- return final_text, docx_path
43
- except Exception as e:
44
- return f"❌ خطأ أثناء الإنتاج: {str(e)}", None
45
-
46
- # واجهة مستقرة (بدون SSR وبدون مسببات الخطأ)
47
- with gr.Blocks(analytics_enabled=False) as demo:
48
- gr.Markdown("# 🖋️ Ling-1T Novel Studio")
49
-
50
- with gr.Row():
51
- with gr.Column():
52
- hf_token = gr.Textbox(label="Hugging Face Token", type="password")
53
- # إزالة أي خصائص إضافية من الملف لضمان الاستقرار
54
- file_input = gr.File(label="Upload DOCX/TXT")
55
- instruction = gr.Textbox(label="Special Instructions", lines=3)
56
- run_btn = gr.Button("🚀 Start Writing", variant="primary")
57
-
58
- with gr.Column():
59
- output_display = gr.Textbox(label="Manuscript Preview", lines=12)
60
- download_link = gr.File(label="Download Final DOCX")
61
-
62
- # القضاء على الخطأ عبر منع الـ API تمامًا لهذا الحدث
63
- run_btn.click(
64
- fn=start_novel_engine,
65
- inputs=[file_input, instruction, hf_token],
66
- outputs=[output_display, download_link],
67
- api_name=False # هذا السطر يمنع Gradio من فحص المكونات برمجياً
68
- )
69
-
70
- if __name__ == "__main__":
71
- # تشغيل مباشر وبسيط
72
- demo.launch(show_api=False)
73
- utils import process_uploaded_file, export_to_docx
74
- from agents_config import create_agents
75
-
76
- # الدالة الأساسية (تأكد أن الأسماء تطابق ما في utils.py)
77
- def process_all(file_obj, manual_text, token):
78
- if not token:
79
- return "❌ يرجى إدخال Token", None
80
-
81
- # قراءة الملف
82
- context = ""
83
- if file_obj is not None:
84
- context = process_uploaded_file(file_obj)
85
-
86
- context += "\n" + manual_text
87
-
88
- if len(context.strip()) < 10:
89
- return "⚠️ النص قصير جداً", None
90
-
91
- try:
92
- agents = create_agents(token)
93
- # إعداد الحوار
94
- groupchat = autogen.GroupChat(
95
- agents=[v for k, v in agents.items() if k != "editor"],
96
- messages=[],
97
- max_round=8
98
  )
99
- manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=agents["editor"].llm_config)
100
 
101
- # التنفيذ
102
- chat_result = agents["editor"].initiate_chat(manager, message=f"أكمل ونسق النص: {context}")
 
103
 
104
- final_text = chat_result.chat_history[-1]['content']
105
- docx_file = export_to_docx(final_text)
106
 
107
- return final_text, docx_file
 
108
  except Exception as e:
109
- return f"❌ خطأ تقني: {str(e)}", None
110
 
111
- # واجهة مستقرة جداً (Minimalist Approach)
112
- with gr.Blocks(ssr=False) as demo: # تعطيل SSR هو مفتاح الحل هنا
113
- gr.Markdown("# 🖋️ Ling-1T Novel Production")
 
 
 
 
 
114
 
115
  with gr.Row():
116
- with gr.Column():
117
- token_input = gr.Textbox(label="HF Token", type="password")
118
- # تبسيط الـ File component لأقصى حد
119
- file_input = gr.File(label="Upload DOCX/TXT")
120
- text_input = gr.Textbox(label="Additional Text", lines=3)
121
- run_btn = gr.Button("🚀 Start")
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- with gr.Column():
124
- output_text = gr.Textbox(label="Manuscript", lines=10)
125
- output_file = gr.File(label="Download DOCX")
 
 
 
 
126
 
127
- run_btn.click(
128
- fn=process_all,
129
- inputs=[file_input, text_input, token_input],
130
- outputs=[output_text, output_file],
131
- api_name=False # منع توليد API لهذا الزر تحديداً
132
  )
133
 
 
 
 
 
 
134
  if __name__ == "__main__":
135
- demo.launch(show_api=False) # إغلاق الـ API تماماً
 
4
  from utils import process_uploaded_file, export_to_docx
5
  from agents_config import create_agents
6
 
7
+ def run_novel_studio(uploaded_file, manual_text, user_token):
8
+ """
9
+ الدالة الرئيسية التي تدير تدفق العمل من الرفع إلى التصدير.
10
+ """
11
+ if not user_token or not user_token.startswith("hf_"):
12
+ return "⚠️ يرجى إدخال Hugging Face Token صحيح (يبدأ بـ hf_).", None
13
+
14
+ # 1. معالجة المدخلات (الملف المرفوع + النص اليدوي)
15
+ file_content = ""
16
+ if uploaded_file is not None:
17
  try:
18
+ file_content = process_uploaded_file(uploaded_file)
19
  except Exception as e:
20
+ return f"❌ خطأ في قراءة ملف docx: {str(e)}", None
21
+
22
+ # دمج المحتوى مع الحفاظ على الأسطر
23
+ combined_context = f"{file_content}\n\n{manual_text}".strip()
24
 
25
+ if len(combined_context) < 10:
26
+ return "⚠️ المحتوى المقدم غير كافٍ. يرجى رفع ملف أو كتابة مسودة.", None
 
27
 
28
  try:
29
+ # 2. إنشاء فريق الوكلاء الـ 9
30
+ agents_dict = create_agents(user_token)
31
+
32
+ # 3. إعداد غرفة النقاش (Group Chat)
33
+ # الوكلاء المساعدون (بدون المدير ورئيس التحرير)
34
+ assistant_agents = [
35
+ agents_dict["analyst"], agents_dict["style_guardian"],
36
+ agents_dict["architect"], agents_dict["draft_writer"],
37
+ agents_dict["humanizer"], agents_dict["continuity_guard"],
38
+ agents_dict["psychologist"], agents_dict["critic"]
39
+ ]
40
+
41
  groupchat = autogen.GroupChat(
42
+ agents=assistant_agents,
43
  messages=[],
44
+ max_round=12,
45
+ speaker_selection_method="auto"
46
  )
 
47
 
48
+ manager = autogen.GroupChatManager(
49
+ groupchat=groupchat,
50
+ llm_config=agents_dict["editor"].llm_config
 
51
  )
52
+
53
+ # 4. إطلاق المهمة بقيادة Ling-1T
54
+ init_message = f"""بصفتي رئيس التحرير، أضع بين أيديكم هذه المسودة.
55
+ المطلوب: تحليلها، إكمال أحداث الفصل التالي، وتنسيقها أدبياً بشكل احترافي.
56
 
57
+ المسودة:
58
+ {combined_context}"""
59
 
60
+ chat_result = agents_dict["editor"].initiate_chat(
61
+ manager,
62
+ message=init_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  )
 
64
 
65
+ # 5. استخراج النص النهائي من Ling-1T وتوليد ملف DOCX
66
+ # نبحث عن آخر رسالة تحتوي على النص المدمج
67
+ final_story_text = chat_result.chat_history[-1]['content']
68
 
69
+ # توليد الملف باستخدام دالة utils المحدثة
70
+ output_file_path = export_to_docx(final_story_text)
71
 
72
+ return final_story_text, output_file_path
73
+
74
  except Exception as e:
75
+ return f"❌ فشل النظام في المعالجة: {str(e)}", None
76
 
77
+ # تصميم واجهة المستخدم (تنسيق احترافي وهادئ)
78
+ with gr.Blocks(theme=gr.themes.Soft(), title="Ling-1T Novel Studio") as demo:
79
+ gr.HTML("""
80
+ <div style="text-align: center;">
81
+ <h1>🖋️ Ling-1T Novel Production Studio</h1>
82
+ <p>نظام ذكاء اصطناعي متعدد الوكلاء لإنتاج وتنسيق الروايات العربية</p>
83
+ </div>
84
+ """)
85
 
86
  with gr.Row():
87
+ with gr.Column(scale=1):
88
+ gr.Markdown("### 🛠️ إعدادات المدخلات")
89
+ token_input = gr.Textbox(
90
+ label="Hugging Face Token",
91
+ type="password",
92
+ placeholder="hf_..."
93
+ )
94
+ file_upload = gr.File(
95
+ label="ارفع مسودة الرواية (.docx, .txt)",
96
+ file_types=[".docx", ".txt"]
97
+ )
98
+ text_area = gr.Textbox(
99
+ label="تعليمات إضافية أو نص تكميلي",
100
+ lines=6,
101
+ placeholder="اكتب هنا إذا كنت تريد توجيه الوكلاء لمسار معين..."
102
+ )
103
+ submit_btn = gr.Button("🚀 إطلاق فريق العمل", variant="primary")
104
 
105
+ with gr.Column(scale=2):
106
+ gr.Markdown("### 📖 المخطوطة النهائية")
107
+ output_markdown = gr.Markdown(
108
+ label="معاينة النص",
109
+ value="ستظهر الرواية هنا بعد اكتمال نقاش الوكلاء..."
110
+ )
111
+ download_btn = gr.File(label="تحميل ملف الوورد المنسق")
112
 
113
+ # ربط الأحداث
114
+ submit_btn.click(
115
+ fn=run_novel_studio,
116
+ inputs=[file_upload, text_area, token_input],
117
+ outputs=[output_markdown, download_btn]
118
  )
119
 
120
+ gr.Markdown("""
121
+ ---
122
+ **ملاحظة:** هذا النظام يستخدم 9 نماذج متخصصة تعمل بالتوازي. قد تستغرق العملية من 1-3 دقائق حسب طول النص.
123
+ """)
124
+
125
  if __name__ == "__main__":
126
+ demo.launch()