Spaces:
Sleeping
Sleeping
Commit
·
ec7832e
1
Parent(s):
f2f02ad
Initial commit
Browse files
app.py
CHANGED
|
@@ -4,110 +4,172 @@ import sqlite3
|
|
| 4 |
from datetime import datetime
|
| 5 |
import torch
|
| 6 |
import gradio as gr
|
| 7 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 8 |
from huggingface_hub import login
|
| 9 |
|
| 10 |
-
# تنظیم
|
| 11 |
-
logging.basicConfig(level=logging.INFO)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
-
# تنظیم توکن
|
| 15 |
-
|
|
|
|
| 16 |
if not hf_token:
|
| 17 |
-
|
|
|
|
| 18 |
login(token=hf_token)
|
| 19 |
-
logger.info("
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 25 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
def init_db():
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
|
|
|
|
| 45 |
def save_to_memory(user_input, task_type, prompt, response):
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
VALUES (?, ?, ?, ?, ?)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
return f"لطفاً یک کد کامل و دقیق در زبان {language} برای حل مسئله زیر بنویس:\n{user_input}"
|
| 58 |
-
elif task_type == "توضیح کد":
|
| 59 |
-
return f"کد زیر به زبان {language} نوشته شده. آن را به فارسی و دقیق توضیح بده:\n{user_input}"
|
| 60 |
-
elif task_type == "دیباگ کد":
|
| 61 |
-
return f"کد زیر در زبان {language} دارای خطاست. لطفاً آن را اصلاح کن و توضیح بده:\n{user_input}"
|
| 62 |
-
elif task_type == "پرومپتسازی":
|
| 63 |
-
return f"با توجه به توضیح زیر، یک پرامپت مناسب برای تولید کد در زبان {language} بساز:\n{user_input}"
|
| 64 |
-
else:
|
| 65 |
-
return user_input
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
def
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
#
|
| 73 |
-
def
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
def show_history
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
# رابط
|
| 91 |
-
def gradio_ui(user_input,
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
return christopher(task_type, user_input, language)
|
| 95 |
|
| 96 |
-
# اجرای برنامه
|
| 97 |
if __name__ == "__main__":
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
import torch
|
| 6 |
import gradio as gr
|
| 7 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 8 |
from huggingface_hub import login
|
| 9 |
|
| 10 |
+
# تنظیم logging
|
| 11 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
+
# تنظیم توکن
|
| 15 |
+
logger.info("Starting application setup")
|
| 16 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 17 |
if not hf_token:
|
| 18 |
+
logger.error("HF_TOKEN not set")
|
| 19 |
+
raise ValueError("HF_TOKEN is required. Set it in Spaces Secrets (Settings > Repository secrets > Add secret > Name: HF_TOKEN).")
|
| 20 |
login(token=hf_token)
|
| 21 |
+
logger.info("Hugging Face login successful")
|
| 22 |
|
| 23 |
+
# لود مدل GPT-Neo-1.3B
|
| 24 |
+
logger.info("Loading EleutherAI/gpt-neo-1.3B model")
|
| 25 |
+
try:
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B", cache_dir="/tmp/hf_cache")
|
| 27 |
+
model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B", cache_dir="/tmp/hf_cache", torch_dtype=torch.float32, device_map="auto")
|
| 28 |
+
code_gen = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512, temperature=0.6, top_p=0.95)
|
| 29 |
+
logger.info("EleutherAI/gpt-neo-1.3B model loaded")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
logger.error(f"Failed to load GPT-Neo model: {e}")
|
| 32 |
+
raise
|
| 33 |
|
| 34 |
+
# آزادسازی حافظه
|
| 35 |
+
import gc
|
| 36 |
+
gc.collect()
|
| 37 |
+
torch.cuda.empty_cache()
|
| 38 |
+
|
| 39 |
+
# مسیر فایل دیتابیس
|
| 40 |
+
DB_PATH = "chris.db"
|
| 41 |
+
|
| 42 |
+
# ایجاد دیتابیس
|
| 43 |
def init_db():
|
| 44 |
+
logger.info("Initializing database")
|
| 45 |
+
try:
|
| 46 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 47 |
+
cursor = conn.cursor()
|
| 48 |
+
cursor.execute('''CREATE TABLE IF NOT EXISTS CHRIS (
|
| 49 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 50 |
+
user_input TEXT,
|
| 51 |
+
task_type TEXT,
|
| 52 |
+
prompt TEXT,
|
| 53 |
+
response TEXT,
|
| 54 |
+
timestamp TEXT
|
| 55 |
+
)''')
|
| 56 |
+
conn.commit()
|
| 57 |
+
logger.info("Database initialized")
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Database error: {e}")
|
| 60 |
+
raise
|
| 61 |
|
| 62 |
+
# ذخیره در دیتابیس
|
| 63 |
def save_to_memory(user_input, task_type, prompt, response):
|
| 64 |
+
logger.info("Saving to database")
|
| 65 |
+
try:
|
| 66 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 67 |
+
cursor = conn.cursor()
|
| 68 |
+
cursor.execute("INSERT INTO CHRIS (user_input, task_type, prompt, response, timestamp) VALUES (?, ?, ?, ?, ?)",
|
| 69 |
+
(user_input, task_type, prompt, response, datetime.now().isoformat()))
|
| 70 |
+
conn.commit()
|
| 71 |
+
logger.info("Saved to DB")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
logger.error(f"DB Save Error: {e}")
|
| 74 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
# دریافت تاریخچه
|
| 77 |
+
def get_history():
|
| 78 |
+
logger.info("Retrieving history from database")
|
| 79 |
+
try:
|
| 80 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 81 |
+
cursor = conn.cursor()
|
| 82 |
+
cursor.execute("SELECT id, user_input, task_type, prompt, response, timestamp FROM CHRIS ORDER BY timestamp DESC")
|
| 83 |
+
rows = cursor.fetchall()
|
| 84 |
+
if not rows:
|
| 85 |
+
return "هیچ تاریخچهای موجود نیست."
|
| 86 |
+
history_text = "=== تاریخچه ===\n"
|
| 87 |
+
for row in rows:
|
| 88 |
+
history_text += f"ID: {row[0]}\n"
|
| 89 |
+
history_text += f"ورودی کاربر: {row[1]}\n"
|
| 90 |
+
history_text += f"نوع کار: {row[2]}\n"
|
| 91 |
+
history_text += f"پرامپت: {row[3]}\n"
|
| 92 |
+
history_text += f"پاسخ: {row[4]}\n"
|
| 93 |
+
history_text += f"زمان: {row[5]}\n"
|
| 94 |
+
history_text += "-" * 50 + "\n"
|
| 95 |
+
return history_text
|
| 96 |
+
except Exception as e:
|
| 97 |
+
logger.error(f"History retrieval error: {e}")
|
| 98 |
+
return f"خطا در دریافت تاریخچه: {e}"
|
| 99 |
|
| 100 |
+
# تولید کد
|
| 101 |
+
def generate_code(text, language):
|
| 102 |
+
logger.info(f"Processing input: {text}, language: {language}")
|
| 103 |
+
try:
|
| 104 |
+
prompt = f"Write a complete, correct, and well-explained code in {language} to: {text}"
|
| 105 |
+
logger.info(f"Generated prompt: {prompt}")
|
| 106 |
+
result = code_gen(prompt, max_new_tokens=512, temperature=0.6, top_p=0.95, do_sample=True)[0]['generated_text']
|
| 107 |
+
|
| 108 |
+
# استخراج کد از خروجی
|
| 109 |
+
lines = result.split('\n')
|
| 110 |
+
code = []
|
| 111 |
+
is_code = False
|
| 112 |
+
for line in lines:
|
| 113 |
+
if line.startswith("```"):
|
| 114 |
+
is_code = not is_code
|
| 115 |
+
continue
|
| 116 |
+
elif is_code:
|
| 117 |
+
code.append(line)
|
| 118 |
+
|
| 119 |
+
code_output = "\n".join(code).strip()
|
| 120 |
+
if not code_output:
|
| 121 |
+
logger.warning("Generated code is empty")
|
| 122 |
+
code_output = "خطا: کد تولیدشده خالی است"
|
| 123 |
+
|
| 124 |
+
logger.info(f"Generated code: {code_output}")
|
| 125 |
+
torch.cuda.empty_cache()
|
| 126 |
+
return prompt, code_output
|
| 127 |
+
except Exception as e:
|
| 128 |
+
logger.error(f"Code generation error: {e}")
|
| 129 |
+
return f"Error prompt: {text}", f"Code generation error: {e}"
|
| 130 |
|
| 131 |
+
# تابع اصلی
|
| 132 |
+
def christopher(user_input, language, show_history):
|
| 133 |
+
logger.info(f"Processing input: {user_input}, language: {language}, show_history: {show_history}")
|
| 134 |
+
try:
|
| 135 |
+
task_type = "تولید کد"
|
| 136 |
+
prompt, response = generate_code(user_input, language)
|
| 137 |
+
if "error" in response.lower():
|
| 138 |
+
history = get_history() if show_history else ""
|
| 139 |
+
return response, history
|
| 140 |
+
save_to_memory(user_input, task_type, prompt, response)
|
| 141 |
+
history = get_history() if show_history else ""
|
| 142 |
+
return response, history
|
| 143 |
+
except Exception as e:
|
| 144 |
+
logger.error(f"Processing error: {e}")
|
| 145 |
+
history = get_history() if show_history else ""
|
| 146 |
+
return f"خطا: {e}", history
|
| 147 |
|
| 148 |
+
# رابط گرادیو
|
| 149 |
+
def gradio_ui(user_input, language, show_history):
|
| 150 |
+
code, history = christopher(user_input, language, show_history)
|
| 151 |
+
return code, history
|
|
|
|
| 152 |
|
|
|
|
| 153 |
if __name__ == "__main__":
|
| 154 |
+
logger.info("Starting application")
|
| 155 |
+
try:
|
| 156 |
+
init_db()
|
| 157 |
+
logger.info("Launching Gradio interface")
|
| 158 |
+
iface = gr.Interface(
|
| 159 |
+
fn=gradio_ui,
|
| 160 |
+
inputs=[
|
| 161 |
+
gr.Textbox(label="توضیح برنامه به فارسی (مثال: یک تابع اعداد زوج)"),
|
| 162 |
+
gr.Dropdown(choices=["Python", "JavaScript", "Java", "C++"], label="زبان برنامهنویسی"),
|
| 163 |
+
gr.Checkbox(label="نمایش تاریخچه درخواستها", value=False)
|
| 164 |
+
],
|
| 165 |
+
outputs=[
|
| 166 |
+
gr.Textbox(label="کد تولیدشده"),
|
| 167 |
+
gr.Textbox(label="تاریخچه درخواستها")
|
| 168 |
+
],
|
| 169 |
+
title="کریستوفر - دستیار کدنویسی",
|
| 170 |
+
description="توضیح برنامه را به فارسی وارد کنید و زبان برنامهنویسی را انتخاب کنید. برای نمایش تاریخچه، گزینه مربوطه را تیک بزنید."
|
| 171 |
+
)
|
| 172 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|
| 173 |
+
except Exception as e:
|
| 174 |
+
logger.error(f"Startup error: {e}")
|
| 175 |
+
raise
|