Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
from fastapi import FastAPI, HTTPException
|
| 3 |
+
from pydantic import BaseModel, HttpUrl, Field
|
| 4 |
+
from typing import List, Dict, Optional, Any, Tuple
|
| 5 |
+
|
| 6 |
+
from helpers.text_blocks import extract_text_from_url
|
| 7 |
+
from helpers.output_clipper import clip_by_ranges
|
| 8 |
+
from parser.assembler import parse_law_from_texts
|
| 9 |
+
from supabase_utils import save_law_to_supabase # استدعاء الدالة لحفظ القانون
|
| 10 |
+
|
| 11 |
+
app = FastAPI(
|
| 12 |
+
title="Text Extractor API",
|
| 13 |
+
description="API لاستخراج النصوص من صفحات الويب مع إمكانية التحكم في النطاقات",
|
| 14 |
+
version="2.1.0"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# -----------------------------
|
| 18 |
+
# نماذج البيانات
|
| 19 |
+
# -----------------------------
|
| 20 |
+
class URLRequest(BaseModel):
|
| 21 |
+
url: HttpUrl
|
| 22 |
+
return_parsed: bool = Field(
|
| 23 |
+
default=False,
|
| 24 |
+
description="إذا True → إرجاع المستند القانوني المحلل، إذا False → إرجاع النصوص الخام"
|
| 25 |
+
)
|
| 26 |
+
save_to_supabase: bool = Field(
|
| 27 |
+
default=False,
|
| 28 |
+
description="إذا True → حفظ المستند القانوني في قاعدة البيانات"
|
| 29 |
+
)
|
| 30 |
+
timeout: int = Field(default=10, ge=1, le=60)
|
| 31 |
+
ranges: Optional[List[List[int]]] = Field(
|
| 32 |
+
default=None,
|
| 33 |
+
description="نطاقات الاستخراج في شكل [[start, end], [start, end]] - اختياري"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
class TextResponse(BaseModel):
|
| 37 |
+
text: str
|
| 38 |
+
|
| 39 |
+
class LegalDocumentResponse(BaseModel):
|
| 40 |
+
raw_texts: Optional[List[TextResponse]] = None
|
| 41 |
+
parsed_document: Optional[Dict[str, Any]] = None
|
| 42 |
+
|
| 43 |
+
# -----------------------------
|
| 44 |
+
# التحقق من صحة النطاقات
|
| 45 |
+
# -----------------------------
|
| 46 |
+
def validate_ranges(ranges: List[List[int]]) -> List[Tuple[int, int]]:
|
| 47 |
+
validated_ranges = []
|
| 48 |
+
for i, range_pair in enumerate(ranges):
|
| 49 |
+
if len(range_pair) != 2:
|
| 50 |
+
raise HTTPException(
|
| 51 |
+
status_code=400,
|
| 52 |
+
detail=f"النطاق رقم {i+1} غير صحيح. كل نطاق يجب أن يحتوي على عنصرين: [start, end]"
|
| 53 |
+
)
|
| 54 |
+
start, end = range_pair
|
| 55 |
+
if not isinstance(start, int) or not isinstance(end, int):
|
| 56 |
+
raise HTTPException(
|
| 57 |
+
status_code=400,
|
| 58 |
+
detail=f"النطاق رقم {i+1} غير صحيح. القيم يجب أن تكون أرقام صحيحة"
|
| 59 |
+
)
|
| 60 |
+
if start < 0 or end <= start:
|
| 61 |
+
raise HTTPException(
|
| 62 |
+
status_code=400,
|
| 63 |
+
detail=f"النطاق رقم {i+1} غير صحيح. النهاية يجب أن تكون أكبر من البداية والبداية >= 0"
|
| 64 |
+
)
|
| 65 |
+
validated_ranges.append((start, end))
|
| 66 |
+
return validated_ranges
|
| 67 |
+
|
| 68 |
+
# -----------------------------
|
| 69 |
+
# نقطة النهاية لاستخراج النصوص / القانون مع حفظ قاعدة البيانات
|
| 70 |
+
# -----------------------------
|
| 71 |
+
@app.post("/extract", response_model=LegalDocumentResponse)
|
| 72 |
+
async def extract_text_endpoint(request: URLRequest):
|
| 73 |
+
try:
|
| 74 |
+
# 1) استخراج جميع النصوص (قائمة قواميس)
|
| 75 |
+
all_texts = await extract_text_from_url(str(request.url), request.timeout)
|
| 76 |
+
|
| 77 |
+
# 2) تطبيق النطاقات إذا وجدت
|
| 78 |
+
if request.ranges:
|
| 79 |
+
validated_ranges = validate_ranges(request.ranges)
|
| 80 |
+
filtered_texts = clip_by_ranges(all_texts, validated_ranges)
|
| 81 |
+
else:
|
| 82 |
+
filtered_texts = all_texts
|
| 83 |
+
|
| 84 |
+
# 3) إذا طلب تحليل القانون
|
| 85 |
+
if request.return_parsed:
|
| 86 |
+
parsed_document = parse_law_from_texts(filtered_texts)
|
| 87 |
+
|
| 88 |
+
# 4) حفظ القانون في Supabase إذا كان save_to_supabase = True
|
| 89 |
+
if request.save_to_supabase:
|
| 90 |
+
save_law_to_supabase(parsed_document["law"])
|
| 91 |
+
parsed_document["saved_to_db"] = True # تحديث المفتاح داخل الاستجابة
|
| 92 |
+
else:
|
| 93 |
+
parsed_document["saved_to_db"] = False
|
| 94 |
+
|
| 95 |
+
return LegalDocumentResponse(parsed_document=parsed_document)
|
| 96 |
+
|
| 97 |
+
# 5) خلاف ذلك: إرجاع النصوص الخام
|
| 98 |
+
return LegalDocumentResponse(raw_texts=filtered_texts)
|
| 99 |
+
|
| 100 |
+
except httpx.RequestError as e:
|
| 101 |
+
raise HTTPException(status_code=400, detail=f"خطأ في جلب الصفحة: {str(e)}")
|
| 102 |
+
except HTTPException:
|
| 103 |
+
raise
|
| 104 |
+
except Exception as e:
|
| 105 |
+
raise HTTPException(status_code=500, detail=f"خطأ في معالجة المحتوى: {str(e)}")
|