Spaces:
Sleeping
Sleeping
fix app temp
Browse files
app.py
CHANGED
|
@@ -27,8 +27,6 @@ import threading
|
|
| 27 |
from datetime import datetime
|
| 28 |
|
| 29 |
# ----- Configuration -----
|
| 30 |
-
"MINI_MODEL_PATH": "/data/mini_model",
|
| 31 |
-
"HF_CACHE_DIR": "/data/huggingface_cache",
|
| 32 |
CONFIG = {
|
| 33 |
"MAX_CONTEXT_TOKENS": 12000,
|
| 34 |
"MAX_AUDIT_ATTEMPTS": 5,
|
|
@@ -47,8 +45,8 @@ CONFIG = {
|
|
| 47 |
"SAVE_INTERVAL": 300,
|
| 48 |
"HF_TOKEN": os.getenv("HF_TOKEN"),
|
| 49 |
"MAX_IMAGE_SIZE": 3e6, # 3MP
|
| 50 |
-
"MINI_MODEL_PATH": "/
|
| 51 |
-
"HF_CACHE_DIR": "/
|
| 52 |
"SYSTEM_PROMPT": """You are an AI development assistant. Follow these rules:
|
| 53 |
1. If request is simple (single file, <50 lines), handle it directly
|
| 54 |
2. For complex requests (multiple files, >50 lines), send to coder
|
|
@@ -63,9 +61,11 @@ os.makedirs(CONFIG["HF_CACHE_DIR"], exist_ok=True)
|
|
| 63 |
logging.basicConfig(level=logging.INFO)
|
| 64 |
logger = logging.getLogger(__name__)
|
| 65 |
|
| 66 |
-
# Initialize database
|
|
|
|
|
|
|
| 67 |
def init_db():
|
| 68 |
-
conn = sqlite3.connect('/
|
| 69 |
c = conn.cursor()
|
| 70 |
c.execute('''CREATE TABLE IF NOT EXISTS sessions
|
| 71 |
(id TEXT PRIMARY KEY, context TEXT, last_updated REAL)''')
|
|
@@ -102,7 +102,7 @@ class HFIntegration:
|
|
| 102 |
for url in endpoints:
|
| 103 |
try:
|
| 104 |
start_time = time.time()
|
| 105 |
-
response = requests.get(f"{url}/health", timeout=5)
|
| 106 |
latency = time.time() - start_time
|
| 107 |
if response.status_code == 200:
|
| 108 |
results[url] = {
|
|
@@ -128,8 +128,8 @@ class HFIntegration:
|
|
| 128 |
repo_type="space"
|
| 129 |
)
|
| 130 |
return f"Saved to Hugging Face Hub: {repo_id}/{os.path.basename(file_path)}"
|
| 131 |
-
except
|
| 132 |
-
logger.error(f"Hugging Face Hub upload failed
|
| 133 |
return None
|
| 134 |
|
| 135 |
# Download fallback model on startup
|
|
@@ -343,11 +343,12 @@ def generate_code_response(prompt, context):
|
|
| 343 |
response = requests.post(
|
| 344 |
endpoint,
|
| 345 |
json={"prompt": prompt, "context": context},
|
| 346 |
-
timeout=15
|
|
|
|
| 347 |
)
|
| 348 |
if response.status_code == 200:
|
| 349 |
return response.json()["code"]
|
| 350 |
-
except:
|
| 351 |
continue
|
| 352 |
|
| 353 |
# Fallback to local model
|
|
@@ -428,21 +429,21 @@ class SessionManager:
|
|
| 428 |
self.last_save = time.time()
|
| 429 |
|
| 430 |
def get_session(self, session_id):
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
|
| 447 |
def update_session(self, session_id, user_input, response, files=None):
|
| 448 |
session = self.get_session(session_id)
|
|
@@ -481,28 +482,29 @@ class SessionManager:
|
|
| 481 |
logger.info(f"Context summarized for session {session_id}")
|
| 482 |
|
| 483 |
def save_sessions(self):
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
|
|
|
| 506 |
|
| 507 |
session_manager = SessionManager()
|
| 508 |
|
|
@@ -601,10 +603,10 @@ def handle_coder_request(prompt, context, session_id):
|
|
| 601 |
|
| 602 |
# Create backup
|
| 603 |
try:
|
| 604 |
-
with open("/
|
| 605 |
f.write(code)
|
| 606 |
-
ExternalServices.github_commit("/
|
| 607 |
-
HFIntegration.save_to_hub("/
|
| 608 |
except Exception as e:
|
| 609 |
logger.error(f"Backup failed: {e}")
|
| 610 |
|
|
@@ -701,9 +703,9 @@ with gr.Blocks(title="AI Development Assistant", theme=gr.themes.Soft()) as demo
|
|
| 701 |
def save_to_drive(session_id):
|
| 702 |
session = session_manager.get_session(session_id)
|
| 703 |
try:
|
| 704 |
-
with open("/
|
| 705 |
json.dump(session, f)
|
| 706 |
-
link = ExternalServices.google_drive_upload("/
|
| 707 |
return f"Saved to Google Drive: {link}" if link else "Save failed"
|
| 708 |
except Exception as e:
|
| 709 |
return f"Error: {str(e)}"
|
|
@@ -711,9 +713,9 @@ with gr.Blocks(title="AI Development Assistant", theme=gr.themes.Soft()) as demo
|
|
| 711 |
def save_to_hf(session_id):
|
| 712 |
session = session_manager.get_session(session_id)
|
| 713 |
try:
|
| 714 |
-
with open("/
|
| 715 |
json.dump(session, f)
|
| 716 |
-
result = HFIntegration.save_to_hub("/
|
| 717 |
return result if result else "Save to Hugging Face failed"
|
| 718 |
except Exception as e:
|
| 719 |
return f"Error: {str(e)}"
|
|
|
|
| 27 |
from datetime import datetime
|
| 28 |
|
| 29 |
# ----- Configuration -----
|
|
|
|
|
|
|
| 30 |
CONFIG = {
|
| 31 |
"MAX_CONTEXT_TOKENS": 12000,
|
| 32 |
"MAX_AUDIT_ATTEMPTS": 5,
|
|
|
|
| 45 |
"SAVE_INTERVAL": 300,
|
| 46 |
"HF_TOKEN": os.getenv("HF_TOKEN"),
|
| 47 |
"MAX_IMAGE_SIZE": 3e6, # 3MP
|
| 48 |
+
"MINI_MODEL_PATH": "/data/mini_model", # تغيير المسار إلى /data
|
| 49 |
+
"HF_CACHE_DIR": "/data/huggingface_cache", # تغيير المسار إلى /data
|
| 50 |
"SYSTEM_PROMPT": """You are an AI development assistant. Follow these rules:
|
| 51 |
1. If request is simple (single file, <50 lines), handle it directly
|
| 52 |
2. For complex requests (multiple files, >50 lines), send to coder
|
|
|
|
| 61 |
logging.basicConfig(level=logging.INFO)
|
| 62 |
logger = logging.getLogger(__name__)
|
| 63 |
|
| 64 |
+
# Initialize database with lock for thread safety
|
| 65 |
+
db_lock = threading.Lock() # إضافة قفل لإدارة الوصول المتزامن
|
| 66 |
+
|
| 67 |
def init_db():
|
| 68 |
+
conn = sqlite3.connect('/data/sessions.db', check_same_thread=False) # تغيير المسار إلى /data
|
| 69 |
c = conn.cursor()
|
| 70 |
c.execute('''CREATE TABLE IF NOT EXISTS sessions
|
| 71 |
(id TEXT PRIMARY KEY, context TEXT, last_updated REAL)''')
|
|
|
|
| 102 |
for url in endpoints:
|
| 103 |
try:
|
| 104 |
start_time = time.time()
|
| 105 |
+
response = requests.get(f"{url}/health", timeout=5, verify=False) # تجاهل التحقق من الشهادات
|
| 106 |
latency = time.time() - start_time
|
| 107 |
if response.status_code == 200:
|
| 108 |
results[url] = {
|
|
|
|
| 128 |
repo_type="space"
|
| 129 |
)
|
| 130 |
return f"Saved to Hugging Face Hub: {repo_id}/{os.path.basename(file_path)}"
|
| 131 |
+
except: # noqa
|
| 132 |
+
logger.error(f"Hugging Face Hub upload failed")
|
| 133 |
return None
|
| 134 |
|
| 135 |
# Download fallback model on startup
|
|
|
|
| 343 |
response = requests.post(
|
| 344 |
endpoint,
|
| 345 |
json={"prompt": prompt, "context": context},
|
| 346 |
+
timeout=15,
|
| 347 |
+
verify=False # تجاهل التحقق من الشهادات
|
| 348 |
)
|
| 349 |
if response.status_code == 200:
|
| 350 |
return response.json()["code"]
|
| 351 |
+
except: # noqa
|
| 352 |
continue
|
| 353 |
|
| 354 |
# Fallback to local model
|
|
|
|
| 429 |
self.last_save = time.time()
|
| 430 |
|
| 431 |
def get_session(self, session_id):
|
| 432 |
+
with db_lock: # استخدام القفل لإدارة الوصول
|
| 433 |
+
if session_id not in self.sessions:
|
| 434 |
+
c = db_conn.cursor()
|
| 435 |
+
c.execute("SELECT context FROM sessions WHERE id=?", (session_id,))
|
| 436 |
+
row = c.fetchone()
|
| 437 |
+
if row:
|
| 438 |
+
self.sessions[session_id] = json.loads(row[0])
|
| 439 |
+
else:
|
| 440 |
+
self.sessions[session_id] = {
|
| 441 |
+
"history": [],
|
| 442 |
+
"context": "",
|
| 443 |
+
"files": {},
|
| 444 |
+
"created_at": time.time()
|
| 445 |
+
}
|
| 446 |
+
return self.sessions[session_id]
|
| 447 |
|
| 448 |
def update_session(self, session_id, user_input, response, files=None):
|
| 449 |
session = self.get_session(session_id)
|
|
|
|
| 482 |
logger.info(f"Context summarized for session {session_id}")
|
| 483 |
|
| 484 |
def save_sessions(self):
|
| 485 |
+
with db_lock: # استخدام القفل لإدارة الوصول
|
| 486 |
+
try:
|
| 487 |
+
c = db_conn.cursor()
|
| 488 |
+
for session_id, data in self.sessions.items():
|
| 489 |
+
serialized = json.dumps({
|
| 490 |
+
"history": data["history"],
|
| 491 |
+
"context": data["context"],
|
| 492 |
+
"files": data["files"],
|
| 493 |
+
"created_at": data.get("created_at", time.time())
|
| 494 |
+
})
|
| 495 |
+
c.execute(
|
| 496 |
+
"REPLACE INTO sessions (id, context, last_updated) VALUES (?, ?, ?)",
|
| 497 |
+
(session_id, serialized, time.time())
|
| 498 |
+
)
|
| 499 |
+
db_conn.commit()
|
| 500 |
+
logger.info("Sessions saved to database")
|
| 501 |
+
|
| 502 |
+
# Backup to Hugging Face Hub
|
| 503 |
+
with open("/data/sessions_backup.json", "w") as f: # تغيير المسار إلى /data
|
| 504 |
+
json.dump(self.sessions, f)
|
| 505 |
+
HFIntegration.save_to_hub("/data/sessions_backup.json", "your_hf_username/sessions_backup")
|
| 506 |
+
except Exception as e:
|
| 507 |
+
logger.error(f"Session save failed: {e}")
|
| 508 |
|
| 509 |
session_manager = SessionManager()
|
| 510 |
|
|
|
|
| 603 |
|
| 604 |
# Create backup
|
| 605 |
try:
|
| 606 |
+
with open("/data/temp_code.py", "w") as f: # تغيير المسار إلى /data
|
| 607 |
f.write(code)
|
| 608 |
+
ExternalServices.github_commit("/data/temp_code.py", f"Code generated for: {prompt}")
|
| 609 |
+
HFIntegration.save_to_hub("/data/temp_code.py", "your_hf_username/code_backups")
|
| 610 |
except Exception as e:
|
| 611 |
logger.error(f"Backup failed: {e}")
|
| 612 |
|
|
|
|
| 703 |
def save_to_drive(session_id):
|
| 704 |
session = session_manager.get_session(session_id)
|
| 705 |
try:
|
| 706 |
+
with open("/data/session_backup.json", "w") as f: # تغيير المسار إلى /data
|
| 707 |
json.dump(session, f)
|
| 708 |
+
link = ExternalServices.google_drive_upload("/data/session_backup.json")
|
| 709 |
return f"Saved to Google Drive: {link}" if link else "Save failed"
|
| 710 |
except Exception as e:
|
| 711 |
return f"Error: {str(e)}"
|
|
|
|
| 713 |
def save_to_hf(session_id):
|
| 714 |
session = session_manager.get_session(session_id)
|
| 715 |
try:
|
| 716 |
+
with open("/data/session_backup.json", "w") as f: # تغيير المسار إلى /data
|
| 717 |
json.dump(session, f)
|
| 718 |
+
result = HFIntegration.save_to_hub("/data/session_backup.json", "your_hf_username/session_backup")
|
| 719 |
return result if result else "Save to Hugging Face failed"
|
| 720 |
except Exception as e:
|
| 721 |
return f"Error: {str(e)}"
|