Spaces:
Sleeping
Sleeping
File size: 11,367 Bytes
3c822e8 e8ef5ba eae09e3 4858aa9 e8ef5ba bc18988 e8ef5ba eae09e3 e8ef5ba 0944764 eae09e3 e8ef5ba eae09e3 e8ef5ba eae09e3 e8ef5ba eae09e3 e8ef5ba eae09e3 e8ef5ba 3c822e8 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 eae09e3 e8ef5ba eae09e3 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba a7b99af e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 03785fb e8ef5ba eae09e3 bc18988 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 e8ef5ba bc18988 3c822e8 e8ef5ba eae09e3 e8ef5ba eae09e3 bc18988 e8ef5ba bc18988 3c822e8 fe376de e8ef5ba 03785fb eae09e3 03785fb | 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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import torch
import os
# تنظیمات مدلها
MODEL_CONFIG = {
"codegen": {
"name": "CodeGen-350M",
"model_name": "Salesforce/codegen-350M-multi"
},
"codellama": {
"name": "CodeLlama-7B",
"model_name": "codellama/CodeLlama-7b-hf"
},
"starcoder": {
"name": "StarCoder2-3B",
"model_name": "bigcode/starcoder2-3b"
}
}
# بارگذاری مدلها
try:
print("🔄 در حال بارگذاری مدل CodeGen...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_CONFIG["codegen"]["model_name"])
model = AutoModelForCausalLM.from_pretrained(MODEL_CONFIG["codegen"]["model_name"])
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
codegen_loaded = True
print("✅ مدل CodeGen بارگذاری شد")
except Exception as e:
print(f"❌ خطا در بارگذاری مدل CodeGen: {e}")
codegen_loaded = False
# بارگذاری مدلهای اختیاری دیگر
try:
print("🔄 در حال بارگذاری مدل StarCoder2...")
starcoder_pipeline = pipeline(
"text-generation",
model=MODEL_CONFIG["starcoder"]["model_name"],
torch_dtype=torch.float16,
device_map="auto"
)
starcoder_loaded = True
print("✅ مدل StarCoder2 بارگذاری شد")
except Exception as e:
print(f"⚠️ خطا در بارگذاری StarCoder2: {e}")
starcoder_loaded = False
# دیکشنری برای ذخیره تاریخچه گفتگو
conversation_history = {}
def generate_with_starcoder(prompt, max_length=500, temperature=0.7):
"""تولید کد با استفاده از StarCoder2"""
try:
enhanced_prompt = f"# Write Python code for: {prompt}\n\n'''\nWrite clean, efficient Python code:\n{prompt}\n'''\n\ndef"
response = starcoder_pipeline(
enhanced_prompt,
max_length=max_length,
temperature=temperature,
do_sample=True,
num_return_sequences=1,
pad_token_id=starcoder_pipeline.tokenizer.eos_token_id
)
generated_text = response[0]['generated_text']
# استخراج فقط بخش کد
if enhanced_prompt in generated_text:
code = generated_text[len(enhanced_prompt):].strip()
else:
code = generated_text.strip()
return code
except Exception as e:
return f"Error with StarCoder: {str(e)}"
def generate_with_codegen(prompt, user_id="default", max_length=300, temperature=0.7):
"""تولید کد با مدل CodeGen"""
try:
# ساخت prompt بهتر برای مدل
enhanced_prompt = f"# Python code for: {prompt}\n'''\nWrite Python code to solve this problem:\n{prompt}\n'''\n\n"
# اضافه کردن تاریخچه اگر وجود دارد
if user_id in conversation_history and conversation_history[user_id]:
history_text = "\n".join([f"Q: {q}\nA: {a}" for q, a in conversation_history[user_id][-3:]])
enhanced_prompt = f"Previous conversation:\n{history_text}\n\nNew request: {prompt}\n\nCode:"
# تولید کد با پارامترهای بهینه
inputs = tokenizer.encode(enhanced_prompt, return_tensors="pt", max_length=512, truncation=True)
with torch.no_grad():
outputs = model.generate(
inputs,
max_length=max_length,
temperature=temperature,
do_sample=True,
pad_token_id=tokenizer.eos_token_id,
num_return_sequences=1,
early_stopping=True
)
generated_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
# استخراج فقط بخش کد
if enhanced_prompt in generated_code:
generated_code = generated_code[len(enhanced_prompt):].strip()
return generated_code
except Exception as e:
return f"Error with CodeGen: {str(e)}"
def chat_with_ai(prompt, user_id="default", language="python", model_choice="codegen", max_length=500, temperature=0.7):
"""تابع اصلی چت با قابلیت انتخاب مدل"""
if not prompt.strip():
return "لطفاً یک درخواست برنامهنویسی وارد کنید."
# تشخیص نوع درخواست
prompt_lower = prompt.lower()
if any(word in prompt_lower for word in ['سلام', 'hi', 'hello', 'سلامتی']):
return "سلام 👋 به دستیار هوشمند برنامهنویسی خوش آمدید! میتوانید از من بخواهید کد بنویسم، باگها را رفع کنم، یا مفاهیم را توضیح دهم."
elif any(word in prompt_lower for word in ['تشکر', 'ممنون', 'thanks']):
return "خوشحالم که مفید بودم! اگر سوال دیگری دارید بپرسید."
elif any(word in prompt_lower for word in ['خداحافظ', 'bye', 'خدانگهدار']):
return "خدانگهدار! اگر باز هم نیاز به کمک داشتید در خدمتم."
else:
# تولید کد بر اساس مدل انتخاب شده
try:
if model_choice == "starcoder" and starcoder_loaded:
code = generate_with_starcoder(prompt, max_length, temperature)
elif model_choice == "codegen" and codegen_loaded:
code = generate_with_codegen(prompt, user_id, max_length, temperature)
else:
# فالبک به مدل دیگر
if codegen_loaded:
code = generate_with_codegen(prompt, user_id, max_length, temperature)
elif starcoder_loaded:
code = generate_with_starcoder(prompt, max_length, temperature)
else:
return "❌ هیچ مدلی در دسترس نیست. لطفاً مدلها را بررسی کنید."
# ذخیره در تاریخچه
if user_id not in conversation_history:
conversation_history[user_id] = []
conversation_history[user_id].append((prompt, code))
# فرمت کردن خروجی
if code and not code.startswith("Error"):
response = f"**🤖 مدل استفاده شده: {MODEL_CONFIG.get(model_choice, {}).get('name', model_choice)}**\n\n"
response += f"**کد تولید شده:**\n```{language}\n{code}\n```\n\n"
response += "💡 *نکته: همیشه کد را تست کنید و برای پروژههای مهم بررسیهای بیشتری انجام دهید.*"
return response
else:
return f"❌ خطا در تولید کد: {code}"
except Exception as e:
return f"خطا در پردازش: {str(e)}"
def clear_history(user_id="default"):
"""پاک کردن تاریخچه گفتگو"""
if user_id in conversation_history:
conversation_history[user_id] = []
return "✅ تاریخچه گفتگو پاک شد."
def get_model_status():
"""دریافت وضعیت مدلها"""
status = {
"CodeGen-350M": "✅ در دسترس" if codegen_loaded else "❌ غیرفعال",
"StarCoder2-3B": "✅ در دسترس" if starcoder_loaded else "❌ غیرفعال",
"مدل پیشفرض": "CodeGen-350M"
}
return status
# رابط Gradio
with gr.Blocks(theme=gr.themes.Soft(), title="دستیار هوشمند برنامهنویسی - Hugging Face") as demo:
gr.Markdown("""
# 🤖 دستیار هوشمند برنامهنویسی
**نسخه Hugging Face - بدون نیاز به API خارجی**
🔥 **پشتیبانی از مدلهای محلی Hugging Face**
""")
with gr.Row():
with gr.Column():
user_id = gr.Textbox(label="شناسه کاربر", value="user_1")
prompt_input = gr.Textbox(
label="درخواست برنامهنویسی خود را وارد کنید",
placeholder="مثال: تابعی بنویس که اعداد اول را پیدا کند...",
lines=3
)
with gr.Row():
model_choice = gr.Dropdown(
choices=["codegen", "starcoder"],
label="انتخاب مدل AI",
value="codegen",
info="CodeGen: سریع | StarCoder: قدرتمند"
)
language_select = gr.Dropdown(
choices=["python", "javascript", "html", "css", "sql"],
label="زبان برنامهنویسی",
value="python"
)
with gr.Row():
temperature = gr.Slider(0.1, 1.0, value=0.7, label="میزان خلاقیت (Temperature)")
max_length = gr.Slider(100, 1000, value=500, step=50, label="حداکثر طول خروجی")
with gr.Row():
submit_btn = gr.Button("🚀 تولید کد", variant="primary")
clear_btn = gr.Button("🧹 پاک کردن تاریخچه", variant="secondary")
status_btn = gr.Button("📊 وضعیت مدلها", variant="secondary")
with gr.Column():
output = gr.Markdown(label="پاسخ دستیار")
status_output = gr.JSON(label="وضعیت سیستم")
# نمونه درخواستهای پیشفرض
gr.Examples(
examples=[
["تابعی بنویس که عدد n را بگیرد و فاکتوریل آن را برگرداند"],
["یک برنامه بنویس که لیستی از اعداد را بگیرد و ماکزیمم را پیدا کند"],
["کلاس ساده برای مدیریت دانشجو در پایتون بنویس"],
["کد HTML برای یک صفحه لاگین ساده بنویس"]
],
inputs=prompt_input
)
# رویدادها
submit_btn.click(
fn=chat_with_ai,
inputs=[prompt_input, user_id, language_select, model_choice, max_length, temperature],
outputs=output
)
clear_btn.click(
fn=clear_history,
inputs=user_id,
outputs=output
)
status_btn.click(
fn=get_model_status,
inputs=[],
outputs=status_output
)
# امکان ارسال با Enter
prompt_input.submit(
fn=chat_with_ai,
inputs=[prompt_input, user_id, language_select, model_choice, max_length, temperature],
outputs=output
)
if __name__ == "__main__":
print("🚀 در حال راهاندازی دستیار هوشمند برنامهنویسی...")
print(f"📊 وضعیت مدلها: {get_model_status()}")
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True
) |