File size: 6,903 Bytes
2e691c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import os
import tempfile
import requests
from PIL import Image
from io import BytesIO
import PyPDF2
from urllib.parse import urlparse
import speech_recognition as sr

# التحقق من وجود المكتبات المطلوبة
try:
    import moviepy.editor as mp
    MOVIEPY_AVAILABLE = True
except ImportError:
    MOVIEPY_AVAILABLE = False

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pydub import AudioSegment
    PYDUB_AVAILABLE = True
except ImportError:
    PYDUB_AVAILABLE = False

try:
    import av
    AV_AVAILABLE = True
except ImportError:
    AV_AVAILABLE = False

# ============= وظائف تحليل الروابط =============
def analyze_url_type(url: str) -> str:
    """تحديد نوع الرابط بناء على النطاق"""
    domain = urlparse(url).netloc.lower()
    if "youtube.com" in domain or "youtu.be" in domain:
        return "YouTube"
    if "github.com" in domain:
        return "GitHub"
    if "twitter.com" in domain or "x.com" in domain:
        return "تغريدة"
    if domain.endswith(".pdf"):
        return "ملف PDF"
    return "موقع ويب عام"

def fix_url(url: str) -> str:
    """إصلاح الروابط الناقصة"""
    if not url.startswith(("http://", "https://")):
        return "https://" + url.lstrip("//")
    return url

def detect_media_type(url: str) -> str:
    """تحديد نوع الملف من امتداده"""
    url = url.lower()
    if url.endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp')):
        return 'image'
    elif url.endswith(('.mp4', '.mov', '.avi', '.webm')):
        return 'video'
    elif url.endswith(('.mp3', '.wav', '.ogg', '.m4a')):
        return 'audio'
    elif url.endswith('.pdf'):
        return 'pdf'
    return 'link'

# ============= وظائف تحليل الملفات =============
def analyze_image_from_url(image_url: str) -> str:
    """تحليل الصور من الروابط"""
    response = requests.get(image_url)
    response.raise_for_status()
    image = Image.open(BytesIO(response.content))
    return f"تحليل الصورة: الحجم {image.size}، الصيغة {image.format}"

def analyze_pdf_from_url(pdf_url: str) -> str:
    """استخراج النص من ملفات PDF"""
    response = requests.get(pdf_url)
    response.raise_for_status()
    with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
        temp_file.write(response.content)
        temp_path = temp_file.name
    
    try:
        with open(temp_path, "rb") as f:
            reader = PyPDF2.PdfReader(f)
            text = "".join([page.extract_text() or "" for page in reader.pages])
        return f"تم استخراج النص التالي من PDF:\n{text[:500]}..."
    finally:
        os.remove(temp_path)

def extract_text_from_audio_file(audio_path: str) -> str:
    """استخراج النص من الملفات الصوتية"""
    recognizer = sr.Recognizer()
    with sr.AudioFile(audio_path) as source:
        audio = recognizer.record(source)
        try:
            return recognizer.recognize_google(audio, language="ar-SA")
        except sr.UnknownValueError:
            return "لم أتمكن من التعرف على الصوت"
        except sr.RequestError:
            return "خطأ في الاتصال بخدمة التعرف على الصوت"

def analyze_audio_from_url(audio_url: str) -> str:
    """تحليل الملفات الصوتية من الروابط"""
    response = requests.get(audio_url)
    response.raise_for_status()
    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
        temp_audio.write(response.content)
        temp_path = temp_audio.name
    
    try:
        text = extract_text_from_audio_file(temp_path)
        return f"نص الصوت:\n{text}"
    finally:
        os.remove(temp_path)

def analyze_video_from_url(video_url: str) -> str:
    """تحليل الفيديو باستخدام moviepy"""
    if not MOVIEPY_AVAILABLE:
        return "مكتبة moviepy غير متوفرة لتحليل الفيديو"

    response = requests.get(video_url)
    response.raise_for_status()
    with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video:
        temp_video.write(response.content)
        video_path = temp_video.name

    audio_path = video_path.replace(".mp4", ".wav")
    try:
        video = mp.VideoFileClip(video_path)
        video.audio.write_audiofile(audio_path, verbose=False, logger=None)
        text = extract_text_from_audio_file(audio_path)
        return f"نص الفيديو:\n{text}"
    finally:
        os.remove(video_path)
        if os.path.exists(audio_path):
            os.remove(audio_path)

# ============= وظائف إضافية لمعالجة الفيديو =============
def process_video_with_ffmpeg():
    """معالجة الفيديو باستخدام ffmpeg (إذا كان متاحًا)"""
    if not has_ffmpeg():
        return "FFmpeg غير متوفر"
    
    try:
        ffmpeg.input('input.mp4').output('output.mp4', ss=10, t=5).run()
        return "تم معالجة الفيديو باستخدام FFmpeg"
    except Exception as e:
        return f"خطأ في معالجة الفيديو: {str(e)}"

def process_video_with_cv2():
    """معالجة الفيديو باستخدام OpenCV (إذا كان متاحًا)"""
    if not CV2_AVAILABLE:
        return "OpenCV غير متوفر"
    
    cap = cv2.VideoCapture('video.mp4')
    results = []
    
    try:
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            # يمكن إضافة معالجة للإطارات هنا
            results.append(frame)
        return "تم معالجة الفيديو باستخدام OpenCV"
    finally:
        cap.release()

def process_video_with_pydub():
    """استخراج الصوت من الفيديو باستخدام pydub (إذا كان متاحًا)"""
    if not PYDUB_AVAILABLE:
        return "pydub غير متوفر"
    
    try:
        sound = AudioSegment.from_file("video.mp4")
        sound.export("audio.mp3", format="mp3")
        return "تم استخراج الصوت من الفيديو"
    except Exception as e:
        return f"خطأ في استخراج الصوت: {str(e)}"

def process_video_with_av():
    """معالجة الفيديو باستخدام PyAV (إذا كان متاحًا)"""
    if not AV_AVAILABLE:
        return "PyAV غير متوفر"
    
    try:
        container = av.open("video.mp4")
        frames = []
        for frame in container.decode(video=0):
            frames.append(frame.to_image())
        return f"تم استخراج {len(frames)} إطار من الفيديو"
    except Exception as e:
        return f"خطأ في معالجة الفيديو: {str(e)}"