Spaces:
Sleeping
Sleeping
| # app.py داخل Hugging Face Space لخدمة البحث | |
| import gradio as gr | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import urllib.parse | |
| import re | |
| # دالة البحث والزحف | |
| def perform_duckduckgo_scrape(query, max_chars=1500): | |
| if not query: | |
| return "الرجاء تقديم استعلام بحث." | |
| encoded_query = urllib.parse.quote(query) | |
| search_url = f"https://duckduckgo.com/html/?q={encoded_query}" | |
| headers = { | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' | |
| } | |
| print(f"--- تلقي طلب بحث عن: '{query}' ---") | |
| scraped_content = "" | |
| try: | |
| response = requests.get(search_url, headers=headers, timeout=20) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| result_snippets = soup.find_all('a', class_='result__snippet') | |
| if not result_snippets: | |
| result_snippets = soup.find_all('div', class_='result__body') | |
| for snippet in result_snippets: | |
| text = snippet.get_text().strip() | |
| if text: | |
| scraped_content += text + "\n" | |
| if not scraped_content and soup.find('meta', {'name': 'description'}): | |
| scraped_content = soup.find('meta', {'name': 'description'})['content'] + "\n" | |
| if len(scraped_content) > max_chars: | |
| scraped_content = scraped_content[:max_chars] + "..." | |
| if scraped_content: | |
| print("معلومات تم استخراجها بنجاح.") | |
| return scraped_content | |
| else: | |
| print("لم يتم العثور على مقتطفات نصية ذات صلة.") | |
| return "لم يتم العثور على معلومات ذات صلة عبر DuckDuckGo." | |
| except Exception as e: | |
| print(f"خطأ أثناء البحث/الزحف: {e}") | |
| return f"حدث خطأ أثناء البحث في الويب: {str(e)}" | |
| # إنشاء واجهة Gradio (هذا هو ما سيوفر نقطة نهاية الـ API) | |
| iface = gr.Interface( | |
| fn=perform_duckduckgo_scrape, | |
| inputs=gr.Textbox(lines=2, label="استعلام البحث (باللغة العربية)"), | |
| outputs=gr.Textbox(lines=10, label="النتائج المستخرجة"), | |
| title="أداة البحث في DuckDuckGo (مقدمة من Pi-1)" | |
| ) | |
| iface.launch(share=False) |