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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import sqlite3
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 9 |
+
from huggingface_hub import login
|
| 10 |
+
|
| 11 |
+
# تنظیم logging برای دیباگ
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
# تنظیم توکن و تایماوت
|
| 16 |
+
logger.info("Starting application setup")
|
| 17 |
+
os.environ["HF_HUB_ETAG_TIMEOUT"] = "30"
|
| 18 |
+
os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] = "30"
|
| 19 |
+
hf_token = os.getenv("HF_TOKEN", "")
|
| 20 |
+
if not hf_token:
|
| 21 |
+
logger.warning("HF_TOKEN not set, may fail to download models")
|
| 22 |
+
login(token=hf_token)
|
| 23 |
+
|
| 24 |
+
# لود مدل برای کدنویسی و دیباگ
|
| 25 |
+
logger.info("Loading CodeT5 model")
|
| 26 |
+
try:
|
| 27 |
+
code_tokenizer = AutoTokenizer.from_pretrained("Salesforce/CodeT5-base")
|
| 28 |
+
code_model = AutoModelForSeq2SeqLM.from_pretrained("Salesforce/CodeT5-base")
|
| 29 |
+
code_gen = pipeline("text2text-generation", model=code_model, tokenizer=code_tokenizer)
|
| 30 |
+
logger.info("CodeT5 model loaded successfully")
|
| 31 |
+
except Exception as e:
|
| 32 |
+
logger.error(f"Failed to load CodeT5 model: {e}")
|
| 33 |
+
raise
|
| 34 |
+
|
| 35 |
+
# لود تنبل مدل برای فارسی
|
| 36 |
+
farsi_model = None
|
| 37 |
+
def load_farsi_model():
|
| 38 |
+
global farsi_model
|
| 39 |
+
if farsi_model is None:
|
| 40 |
+
logger.info("Loading DistilBERT model")
|
| 41 |
+
try:
|
| 42 |
+
farsi_model = pipeline("text-generation", model="distilbert-base-multilingual-cased", max_new_tokens=512)
|
| 43 |
+
logger.info("DistilBERT model loaded successfully")
|
| 44 |
+
except Exception as e:
|
| 45 |
+
logger.error(f"Failed to load DistilBERT model: {e}")
|
| 46 |
+
raise
|
| 47 |
+
return farsi_model
|
| 48 |
+
|
| 49 |
+
# ایجاد دیتابیس
|
| 50 |
+
def init_db():
|
| 51 |
+
db_path = os.getenv("DB_PATH", "chris.db")
|
| 52 |
+
logger.info(f"Initializing database at {db_path}")
|
| 53 |
+
try:
|
| 54 |
+
with sqlite3.connect(db_path) as conn:
|
| 55 |
+
cursor = conn.cursor()
|
| 56 |
+
cursor.execute('''CREATE TABLE IF NOT EXISTS CHRIS (
|
| 57 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 58 |
+
user_input TEXT,
|
| 59 |
+
task_type TEXT,
|
| 60 |
+
prompt TEXT,
|
| 61 |
+
response TEXT,
|
| 62 |
+
timestamp TEXT
|
| 63 |
+
)''')
|
| 64 |
+
conn.commit()
|
| 65 |
+
logger.info("Database initialized")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.error(f"Database initialization error: {e}")
|
| 68 |
+
raise
|
| 69 |
+
|
| 70 |
+
# ذخیره در حافظه
|
| 71 |
+
def save_to_memory(user_input, task_type, prompt, response):
|
| 72 |
+
try:
|
| 73 |
+
with sqlite3.connect(os.getenv("DB_PATH", "chris.db")) as conn:
|
| 74 |
+
cursor = conn.cursor()
|
| 75 |
+
cursor.execute("INSERT INTO CHRIS (user_input, task_type, prompt, response, timestamp) VALUES (?, ?, ?, ?, ?)",
|
| 76 |
+
(user_input, task_type, prompt, response, datetime.now().isoformat()))
|
| 77 |
+
conn.commit()
|
| 78 |
+
logger.info("Saved to DB")
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"DB Save Error: {e}")
|
| 81 |
+
|
| 82 |
+
# مدل ترجمه و ساخت پرامپت
|
| 83 |
+
def translate_and_prompt(text, language):
|
| 84 |
+
try:
|
| 85 |
+
model = load_farsi_model()
|
| 86 |
+
full_prompt = f"""شما یک دستیار برنامهنویسی هستید که به فارسی مسلط است. متن زیر را به انگلیسی ترجمه کنید و یک پرامپت مناسب برای تولید کد در زبان {language} بنویسید:
|
| 87 |
+
|
| 88 |
+
متن: {text}
|
| 89 |
+
زبان برنامهنویسی: {language}
|
| 90 |
+
"""
|
| 91 |
+
result = model(full_prompt, max_new_tokens=300)
|
| 92 |
+
return result[0]['generated_text']
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.error(f"Translation Error: {e}")
|
| 95 |
+
return f"Error in translation: {e}"
|
| 96 |
+
|
| 97 |
+
# تولید کد
|
| 98 |
+
def generate_code(prompt):
|
| 99 |
+
try:
|
| 100 |
+
result = code_gen(prompt, max_length=512, num_beams=5)
|
| 101 |
+
return result[0]['generated_text']
|
| 102 |
+
except Exception as e:
|
| 103 |
+
logger.error(f"Code generation error: {e}")
|
| 104 |
+
return f"Code generation error: {e}"
|
| 105 |
+
|
| 106 |
+
# تابع اصلی
|
| 107 |
+
def christopher(task_type, user_input, language):
|
| 108 |
+
logger.info(f"Processing task: {task_type}, input: {user_input}, language: {language}")
|
| 109 |
+
try:
|
| 110 |
+
if task_type == "ترجمه و پرامپتسازی":
|
| 111 |
+
response = translate_and_prompt(user_input, language)
|
| 112 |
+
save_to_memory(user_input, task_type, "-", response)
|
| 113 |
+
return response
|
| 114 |
+
|
| 115 |
+
elif task_type == "نوشتن کد کامل":
|
| 116 |
+
prompt = f"Write a complete, correct and well-explained code in {language} to: {user_input}"
|
| 117 |
+
response = generate_code(prompt)
|
| 118 |
+
save_to_memory(user_input, task_type, prompt, response)
|
| 119 |
+
return response
|
| 120 |
+
|
| 121 |
+
elif task_type == "دیباگ کد":
|
| 122 |
+
prompt = f"Debug the following {language} code and provide a fixed version with explanations:\n\n{user_input}"
|
| 123 |
+
response = generate_code(prompt)
|
| 124 |
+
save_to_memory(user_input, task_type, prompt, response)
|
| 125 |
+
return response
|
| 126 |
+
|
| 127 |
+
elif task_type == "توضیح کد به فارسی":
|
| 128 |
+
prompt = f"لطفاً کد زیر که به زبان {language} نوشته شده را به فارسی توضیح دهید:\n\n{user_input}"
|
| 129 |
+
response = load_farsi_model()(prompt, max_new_tokens=512)[0]['generated_text']
|
| 130 |
+
save_to_memory(user_input, task_type, prompt, response)
|
| 131 |
+
return response
|
| 132 |
+
|
| 133 |
+
elif task_type == "نمایش تاریخچه":
|
| 134 |
+
with sqlite3.connect(os.getenv("DB_PATH", "chris.db")) as conn:
|
| 135 |
+
cursor = conn.cursor()
|
| 136 |
+
cursor.execute("SELECT user_input, task_type, prompt, response, timestamp FROM CHRIS ORDER BY id DESC LIMIT 10")
|
| 137 |
+
records = cursor.fetchall()
|
| 138 |
+
history = "\n\n".join([f"{r[4]} | [{r[1]}]\nInput: {r[0]}\nPrompt: {r[2]}\nResponse:\n{r[3]}" for r in records])
|
| 139 |
+
return history
|
| 140 |
+
except Exception as e:
|
| 141 |
+
logger.error(f"Christopher task error: {e}")
|
| 142 |
+
return f"خطا: {e}"
|
| 143 |
+
return "نوع درخواست نامعتبر است."
|
| 144 |
+
|
| 145 |
+
# اجرای گرافیکی با Gradio
|
| 146 |
+
def gradio_ui(user_input, task_type, language):
|
| 147 |
+
return christopher(task_type, user_input, language)
|
| 148 |
+
|
| 149 |
+
# اجرای برنامه
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
logger.info("Starting application")
|
| 152 |
+
try:
|
| 153 |
+
init_db()
|
| 154 |
+
logger.info("Launching Gradio interface")
|
| 155 |
+
iface = gr.Interface(
|
| 156 |
+
fn=gradio_ui,
|
| 157 |
+
inputs=[
|
| 158 |
+
gr.Textbox(label="ورودی یا کد شما"),
|
| 159 |
+
gr.Dropdown(choices=["ترجمه و پرامپتسازی", "نوشتن کد کامل", "دیباگ کد", "توضیح کد به فارسی", "نمایش تاریخچه"], label="انتخاب عملکرد"),
|
| 160 |
+
gr.Textbox(label="زبان برنامهنویسی (مثلاً Python, JavaScript)")
|
| 161 |
+
],
|
| 162 |
+
outputs=gr.Textbox(label="پاسخ کریستوفر"),
|
| 163 |
+
title="کریستوفر - دستیار کدنویسی هوشمند",
|
| 164 |
+
description="۵ عملکرد: ترجمه، تولید کد، دیباگ، توضیح، نمایش تاریخچه. مدلهای مورد استفاده: CodeT5 و DistilBERT"
|
| 165 |
+
)
|
| 166 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|
| 167 |
+
except Exception as e:
|
| 168 |
+
logger.error(f"Application startup error: {e}")
|
| 169 |
+
raise
|