File size: 7,862 Bytes
2c062aa
 
9d77ab2
 
2c062aa
9d77ab2
 
 
 
 
 
 
 
 
 
 
 
 
2c062aa
 
 
 
 
 
 
 
 
 
 
 
9d77ab2
 
 
 
2c062aa
 
9d77ab2
2c062aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d77ab2
 
 
 
 
 
 
 
 
 
 
2c062aa
 
 
 
 
 
 
 
 
 
 
9d77ab2
 
2c062aa
 
 
 
 
 
9d77ab2
2c062aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d77ab2
 
 
2c062aa
 
 
 
 
 
9d77ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c062aa
9d77ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-

import os
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import gradio as gr
import spaces

# Load system prompt from file
def load_system_prompt():
    try:
        with open('system_prompt.txt', 'r', encoding='utf-8') as f:
            return f.read().strip()
    except FileNotFoundError:
        return "أنت مساعد ذكي مفيد."

DEFAULT_SYSTEM_PROMPT = load_system_prompt()

model_path = "inceptionai/jais-adapted-7b-chat"

# Jais chat prompts from documentation
prompt_eng = """### Instruction:Your name is 'Jais', and you are named after Jebel Jais, the highest mountain in UAE. You were made by 'Inception' in the UAE. You are a helpful, respectful, and honest assistant. Always answer as helpfully as possible, while being safe. Complete the conversation between [|Human|] and [|AI|]:
### Input: [|Human|] {Question}
[|AI|]
### Response :"""

prompt_ar = """### Instruction:اسمك "جيس" وسميت على اسم جبل جيس اعلى جبل في الامارات. تم بنائك بواسطة Inception في الإمارات. أنت مساعد مفيد ومحترم وصادق. أجب دائمًا بأكبر قدر ممكن من المساعدة، مع الحفاظ على البقاء أمناً. أكمل المحادثة بين [|Human|] و[|AI|] :
### Input:[|Human|] {Question}
[|AI|]
### Response :"""

# إذا كان فيه HF_TOKEN في البيئة
hf_token = os.getenv("HF_TOKEN")

device = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(model_path, token=hf_token)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", trust_remote_code=True, token=hf_token)

if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

def get_response(text, tokenizer=tokenizer, model=model):
    """نفس الدالة من documentation مع تعديل لـ chat model"""
    tokenized = tokenizer(text, return_tensors="pt")
    input_ids, attention_mask = tokenized['input_ids'].to(device), tokenized['attention_mask'].to(device)
    input_len = input_ids.shape[-1]
    generate_ids = model.generate(
        input_ids,
        attention_mask=attention_mask,
        top_p=0.9,
        temperature=0.3,
        max_length=2048,
        min_length=input_len + 4,
        repetition_penalty=1.2,
        do_sample=True,
        pad_token_id=tokenizer.pad_token_id
    )
    response = tokenizer.batch_decode(
        generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
    )[0]
    response = response.split("### Response :")[-1].lstrip()
    return response

def format_conversation_history(chat_history):
    messages = []
    for item in chat_history:
        role = item["role"]
        content = item["content"]
        if isinstance(content, list):
            content = content[0]["text"] if content and "text" in content[0] else str(content)
        messages.append({"role": role, "content": content})
    return messages

def detect_language(text):
    """Simple language detection - Arabic vs English"""
    arabic_chars = sum(1 for char in text if '\u0600' <= char <= '\u06FF')
    total_chars = len(text.replace(' ', ''))

    if total_chars == 0:
        return 'ar'  # default to Arabic

    arabic_ratio = arabic_chars / total_chars
    return 'ar' if arabic_ratio > 0.3 else 'en'

@spaces.GPU()
def generate_response(input_data, chat_history, max_new_tokens, temperature, top_p, top_k, repetition_penalty):
    # Detect language of the current question
    lang = detect_language(input_data)
    prompt_template = prompt_ar if lang == 'ar' else prompt_eng

    # Build conversation for Jais format
    conversation_parts = []

    # Add system prompt as part of the instruction (keep it short for Jais)
    system_instruction = "اسمك \"أليكس\" وأنت مساعد خدمة العملاء في شركة TechSolutions. مهمتك مساعدة العملاء في حل مشاكلهم مع المنتجات والإجابة عن أسئلتهم حول الخدمات. كن ودوداً وصبوراً ومحترماً. أجب بالعربية أو الإنجليزية حسب تفضيل العميل. ابدأ بالتحية وكن مباشراً في الحلول."

    # Add chat history
    if chat_history:
        for item in chat_history:
            role = item["role"]
            content = item["content"]
            if isinstance(content, list):
                content = content[0]["text"] if content and "text" in content[0] else str(content)

            if role == "user":
                conversation_parts.append(f"[|Human|] {content}")
            elif role == "assistant":
                conversation_parts.append(f"[|AI|] {content}")

    # Add current user message
    conversation_parts.append(f"[|Human|] {input_data}")
    conversation_parts.append("[|AI|]")

    # Join conversation
    conversation = "\n".join(conversation_parts)

    # Create full prompt using Jais format with our system prompt
    full_prompt = f"### Instruction:{system_instruction}\n### Input:{conversation}\n### Response :"

    try:
        # استخدام دالة get_response من documentation
        response = get_response(full_prompt)

        # استخراج الرد الجديد فقط (بعد "### Response :")
        if "### Response :" in response:
            response = response.split("### Response :")[-1].strip()

        if not response:
            response = "أهلاً! أنا أليكس مساعد خدمة العملاء. كيف أقدر أساعدك اليوم؟"

        yield response

    except Exception as e:
        print(f"Error in generate_response: {e}")
        import traceback
        print(traceback.format_exc())
        yield "أهلاً! أنا أليكس مساعد خدمة العملاء. كيف أقدر أساعدك اليوم؟"

demo = gr.ChatInterface(
    fn=generate_response,
    additional_inputs=[
        gr.Slider(label="الحد الأقصى للكلمات الجديدة", minimum=64, maximum=4096, step=1, value=2048),
        gr.Slider(label="درجة الحرارة", minimum=0.1, maximum=2.0, step=0.1, value=0.7),
        gr.Slider(label="Top-p", minimum=0.05, maximum=1.0, step=0.05, value=0.9),
        gr.Slider(label="Top-k", minimum=1, maximum=100, step=1, value=50),
        gr.Slider(label="عقوبة التكرار", minimum=1.0, maximum=2.0, step=0.05, value=1.0)
    ],
    examples=[
        [{"text": "النت عندي معطل من الصبح، تقدر تساعدني؟"}],
        [{"text": "عندي مشكلة بالاتصال بالواي فاي"}],
        [{"text": "شنو الباقات المتوفرة عندكم؟"}],
        [{"text": "كيف أعيد ضبط الجهاز؟"}],
        [{"text": "My device is not working properly"}],
    ],
    cache_examples=False,
    type="messages",
    title="دعم عملاء TechSolutions - مساعد أليكس (العراقي)",
    description="""🤖 مساعد خدمة عملاء ذكي لـ TechSolutions

✨ المميزات:
- 🌐 دعم ثنائي اللغة (عربي وإنجليزي)
- 💬 لهجة محادثة طبيعية
- 🔧 دعم فني واستكشاف الأخطاء
- 📋 معلومات الخدمات والإرشاد
- 🎯 مدعوم بـ موديل Unsloth Meta-Llama-3.1-8B-Instruct (مع تحسينات الأداء)

احجي مع أليكس لحل مشاكلك التقنية، استفسر عن الخدمات، أو احصل على معلومات المنتجات.""",
    fill_height=True,
    textbox=gr.Textbox(
        label="اكتب رسالتك هنا",
        placeholder="مثال: عندي مشكلة بالجهاز..."
    ),
    stop_btn="إيقاف التوليد",
    multimodal=False,
    theme=gr.themes.Soft()
)

if __name__ == "__main__":
    demo.launch()