FECUOY commited on
Commit
a8da7ed
·
verified ·
1 Parent(s): c1e79ed

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +26 -76
utils.py CHANGED
@@ -1,84 +1,34 @@
1
- import re
 
2
  from huggingface_hub import HfApi
3
 
4
- def validate_hf_token(token: str):
5
- """
6
- التحقق من صحة توكن المستخدم وجلب بيانات الحساب لضمان صلاحية الاستهلاك.
7
- """
8
- if not token or not token.startswith("hf_"):
9
- return False, "⚠️ عذراً، يجب إدخال Hugging Face Token صحيح يبدأ بـ hf_"
10
-
11
- try:
12
- api = HfApi(token=token)
13
- user_info = api.whoami()
14
- username = user_info.get('name', 'User')
15
- return True, f"✅ تم الاتصال بنجاح. مرحباً كاتبنا المبدع: {username}"
16
- except Exception as e:
17
- return False, f"❌ خطأ في التحقق من الرمز: {str(e)}"
18
-
19
- def clean_ai_output(text: str):
20
- """
21
- تنظيف مخرجات النماذج من العلامات الزائدة أو النصوص التقنية
22
- التي قد تظهر أثناء توليد النص الروائي.
23
- """
24
- if not text:
25
  return ""
26
 
27
- # إزالة علامات التفكير أو الوسوم التقنية إن وجدت
28
- text = re.sub(r'<\|thought\|>.*?<\|/thought\|>', '', text, flags=re.DOTALL)
29
- text = re.sub(r'\[SYSTEM_NOTE\].*?\[/SYSTEM_NOTE\]', '', text, flags=re.DOTALL)
30
-
31
- return text.strip()
32
-
33
- def format_chat_history(chat_history):
34
- """
35
- تنسيق المحادثة الجماعية بين الوكلاء الـ 9 لعرضها في واجهة Gradio.
36
- يتم استخدام Markdown لتمييز الأدوار.
37
- """
38
- if not chat_history:
39
- return "جاري بدء النقاش بين الوكلاء..."
40
 
41
- formatted_output = ""
 
 
42
 
43
- # أيقونات مخصصة لكل وكيل لتمييزهم بصرياً
44
- icons = {
45
- "Analyst": "🔍",
46
- "Style_Guardian": "🛡️",
47
- "Architect": "📐",
48
- "Draft_Writer": "✍️",
49
- "Humanizer": "🎭",
50
- "Continuity_Guard": "⏳",
51
- "Psychologist": "🧠",
52
- "Critic": "⚖️",
53
- "Editor_In_Chief": "👑"
54
- }
55
-
56
- for message in chat_history:
57
- role = message.get("name", "Unknown")
58
- content = message.get("content", "")
59
-
60
- if not content:
61
- continue
62
-
63
- icon = icons.get(role, "🤖")
64
-
65
- # تنسيق مخصص لكل رسالة
66
- formatted_output += f"### {icon} {role}\n"
67
- formatted_output += f"{content}\n\n"
68
- formatted_output += "---\n\n"
69
-
70
- return formatted_output
71
-
72
- def extract_final_story(chat_history):
73
- """
74
- محاولة استخراج النص الروائي النهائي المدمج من رسالة Editor-in-Chief الأخيرة.
75
- """
76
- if not chat_history:
77
- return "لم يتم توليد نص بعد."
78
 
79
- # نبحث عن آخر رسالة من رئيس التحرير أو آخر رسالة في الحوار
80
- for message in reversed(chat_history):
81
- if message.get("name") == "Editor_In_Chief" or message.get("role") == "assistant":
82
- return clean_ai_output(message.get("content", ""))
 
83
 
84
- return "فشل استخراج النص النهائي."
 
 
1
+ import os
2
+ from docx import Document
3
  from huggingface_hub import HfApi
4
 
5
+ def process_uploaded_file(file):
6
+ """قراءة محتوى الملف المرفوع وتحويله إلى نص للمعالجة"""
7
+ if file is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  return ""
9
 
10
+ file_path = file.name
11
+ if file_path.endswith('.txt'):
12
+ with open(file_path, 'r', encoding='utf-8') as f:
13
+ return f.read()
14
+ elif file_path.endswith('.docx'):
15
+ doc = Document(file_path)
16
+ return "\n".join([para.text for para in doc.paragraphs])
17
+ return ""
 
 
 
 
 
18
 
19
+ def export_to_docx(final_text, filename="Final_Novel_Draft.docx"):
20
+ """تحويل مخرجات Ling-1T إلى ملف Word منسق واحترافي"""
21
+ doc = Document()
22
 
23
+ # إضافة عنوان الرواية بتنسيق مميز
24
+ title = doc.add_heading('المخطوطة النهائية للرواية', 0)
25
+ title.alignment = 1 # محاذاة للوسط
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # تنظيف النص وإضافة الفقرات
28
+ paragraphs = final_text.split('\n')
29
+ for p in paragraphs:
30
+ if p.strip():
31
+ doc.add_paragraph(p)
32
 
33
+ doc.save(filename)
34
+ return filename