cargo / app.py
lljz66's picture
Create app.py
73f5501 verified
from fastapi import FastAPI, Query
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import os
import json
import shutil
import git
import time
app = FastAPI(title="Uspoo MVP")
# ========== تحميل الـ Rust core library ==========
import uspoo_core # المكتبة التي بنيناها بـ PyO3
# ========== دوال الفهرسة والبحث ==========
INDEX_PATH = "./uspoo_index"
REPO_PATH = "./repo_data"
@app.on_event("startup")
async def startup():
"""يستنسخ المستودع ويبنيه عند بدء التشغيل"""
# استنساخ مستودع خفيف (Flask هو مثال جيد لأنه سهل وسريع)
if not os.path.exists(REPO_PATH):
print(f"⬇️ استنساخ المستودع...")
repo_url = "https://github.com/pallets/flask.git"
git.Repo.clone_from(repo_url, REPO_PATH, depth=1)
print(f"✅ تم الاستنساخ")
# بناء الفهرس (يتم مرة واحدة، ويتجاهل إذا كان موجوداً)
if not os.path.exists(INDEX_PATH):
print(f"🔨 بناء فهرس Tantivy...")
start = time.time()
count = uspoo_core.index_directory(INDEX_PATH, REPO_PATH)
print(f"✅ تمت فهرسة {count} ملف في {time.time()-start:.1f}s")
# ========== واجهة HTML ==========
HTML = """
<html>
<head><title>Uspoo Code Search (Rust-powered MVP)</title>
<style>
body { font-family: system-ui, sans-serif; margin: 40px; background: #1e1e1e; color: #ccc; }
input[type=text] { width: 400px; padding: 10px; background: #333; border: 1px solid #555; color: white; border-radius: 5px; }
input[type=submit] { padding: 10px 20px; background: #007acc; border: none; color: white; border-radius: 5px; cursor: pointer; }
.result { background: #2d2d2d; padding: 10px; margin: 5px 0; border-radius: 3px; }
.result a { color: #4ec9b0; text-decoration: none; }
</style>
</head>
<body>
<h2>🔍 Uspoo Code Search (MVP with Rust + Tantivy)</h2>
<form method="GET">
<input type="text" name="q" placeholder="ابحث في الكود..." value="{{ query }}">
<input type="submit" value="بحث">
</form>
<div>
{% if results is not none %}
<p>تم العثور على {{ results|length }} نتيجة:</p>
{% for path in results %}
<div class="result">📄 {{ path }}</div>
{% else %}
<p>لم يتم العثور على نتائج.</p>
{% endfor %}
{% endif %}
</div>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
async def home(q: str = Query(None)):
results = None
if q:
results = uspoo_core.search(INDEX_PATH, q)
# حقن القيم في قالب HTML
html = HTML \
.replace("{{ query }}", q or "") \
.replace("{{ results|length }}", str(len(results) if results else 0))
if results:
results_html = "".join(f'<div class="result">📄 {r}</div>' for r in results)
else:
results_html = "<p>لم يتم العثور على نتائج.</p>" if q else ""
html = html.replace("{% for path in results %}...{% endfor %}", results_html)
return html