chatbox / app2.py
anaspro
upadte
2c062aa
raw
history blame
7.86 kB
# -*- 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()