Moharek commited on
Commit
b4a3e73
·
1 Parent(s): 7646e5b

Fix frontend routing

Browse files
Files changed (1) hide show
  1. app.py +170 -178
app.py CHANGED
@@ -1,209 +1,201 @@
1
  """
2
  Moharek GEO Platform - Hugging Face Space
3
- Complete integration of FastAPI backend + Gradio frontend
4
  """
5
 
6
  import os
7
  import sys
8
  from pathlib import Path
9
 
10
- # Add paths
11
  sys.path.insert(0, str(Path(__file__).parent))
12
 
13
  import gradio as gr
14
- import uvicorn
15
  from fastapi.staticfiles import StaticFiles
16
- from fastapi.responses import FileResponse
17
 
18
- # Import the main FastAPI app
19
  from server.api import app as fastapi_app
20
 
21
  # Configuration
22
- PORT = int(os.environ.get("PORT", 7860))
23
- HOST = "0.0.0.0"
24
-
25
- print("🚀 Moharek GEO Platform Starting...")
26
- print(f"📍 Working directory: {Path.cwd()}")
27
- print(f"🌐 Server: http://{HOST}:{PORT}")
28
-
29
- # Mount frontend files at /app prefix
30
  frontend_path = Path(__file__).parent / "frontend"
 
 
31
  if frontend_path.exists():
32
- print(f"📁 Frontend path: {frontend_path}")
 
33
 
34
- # Mount static files
35
- fastapi_app.mount("/frontend", StaticFiles(directory=str(frontend_path)), name="frontend_static")
 
 
36
 
37
- # Serve frontend pages at /app/* - MUST be defined before Gradio mounting
38
- from fastapi.responses import JSONResponse
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- @fastapi_app.get("/app/")
41
- async def serve_app_index():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  index_file = frontend_path / "index.html"
43
  if index_file.exists():
44
- return FileResponse(str(index_file))
45
- return JSONResponse({"error": "index.html not found"}, status_code=404)
46
-
47
- @fastapi_app.get("/app/{page}")
48
- async def serve_app_page(page: str):
49
- # Handle both .html and without extension
50
- if not page.endswith('.html'):
51
- page = page + '.html'
52
-
53
- file_path = frontend_path / page
54
- if file_path.exists():
55
- return FileResponse(str(file_path))
56
-
57
- return JSONResponse({"error": f"Page {page} not found"}, status_code=404)
58
 
59
  # Create Gradio interface
60
- def create_gradio_ui():
61
- with gr.Blocks(
62
- title="Moharek GEO Platform",
63
- theme=gr.themes.Soft(primary_hue="teal", secondary_hue="green"),
64
- css="""
65
- .gradio-container {
66
- background: linear-gradient(135deg, #071f21 0%, #0F4246 100%);
67
- font-family: 'Cairo', sans-serif;
68
- }
69
- .gr-button-primary {
70
- background: linear-gradient(135deg, #c8f04e, #a8d630) !important;
71
- color: #071f21 !important;
72
- font-weight: 900 !important;
73
- }
74
- """
75
- ) as demo:
76
- gr.Markdown("""
77
- # 🚀 محرك — Moharek GEO Platform
78
-
79
- ## منصة تحسين محركات البحث بالذكاء الاصطناعي
80
-
81
- **Search Growth System** — 5 محركات متكاملة
82
-
83
- ---
84
-
85
- ### 🎯 الميزات الرئيسية:
86
-
87
- - 📈 **SEO Engine** — تحسين محركات البحث
88
- - 🤖 **AI Visibility Engine** — الظهور في ChatGPT
89
- - 🎯 **Ads Engine** — إدارة الإعلانات
90
- - 📝 **Content Engine** — إنشاء المحتوى
91
- - ⭐ **Trust Engine** — بناء الثقة
92
- """)
93
-
94
- with gr.Row():
95
- with gr.Column(scale=2):
96
- gr.Markdown("### 🔍 ابدأ التحليل")
97
-
98
- url_input = gr.Textbox(
99
- label="رابط الموقع",
100
- placeholder="https://example.com"
101
- )
102
-
103
- org_input = gr.Textbox(
104
- label="اسم الشركة",
105
- placeholder="اسم شركتك"
106
- )
107
-
108
- pages_slider = gr.Slider(
109
- minimum=10,
110
- maximum=100,
111
- value=50,
112
- step=10,
113
- label="عدد الصفحات"
114
- )
115
-
116
- analyze_btn = gr.Button("🚀 ابدأ التحليل", variant="primary")
117
 
118
- with gr.Column(scale=1):
119
- gr.Markdown("""
120
- ### 📊 ماذا ستحصل؟
121
-
122
- ✅ تحليل SEO شامل
123
- ✅ تقييم GEO Score
124
- ✅ استخراج الكلمات المفتاحية
125
- ✅ توصيات قابلة للتنفيذ
126
-
127
- ---
128
-
129
- ### 🌐 الوصول الكامل
130
-
131
- 👉 [لوحة التحكم](/app/portal.html)
132
- 👉 [تسجيل الدخول](/app/login.html)
133
- 👉 [API Docs](/api/docs)
134
- """)
135
-
136
- status_output = gr.Textbox(label="الحالة", interactive=False, lines=3)
137
- json_output = gr.JSON(label="النتائج")
138
-
139
- def analyze(url, org, pages):
140
- if not url or not url.startswith('http'):
141
- return "❌ الرجاء إدخال رابط صحيح", None
142
 
143
- try:
144
- import requests
145
- response = requests.post(
146
- f"http://localhost:{PORT}/api/jobs",
147
- json={
148
- "url": url,
149
- "org_name": org or "Unknown",
150
- "org_url": url,
151
- "max_pages": int(pages),
152
- "runs": 1
153
- },
154
- timeout=30
155
- )
156
-
157
- if response.status_code == 200:
158
- data = response.json()
159
- if data.get("ok"):
160
- job_id = data.get("job_id")
161
- return f"✅ تم إنشاء التحليل!\n\nJob ID: {job_id}", data
162
- return f"❌ خطأ: {data.get('error')}", None
163
- return f"❌ خطأ: {response.status_code}", None
164
- except Exception as e:
165
- return f"❌ خطأ: {str(e)}", None
166
-
167
- analyze_btn.click(
168
- fn=analyze,
169
- inputs=[url_input, org_input, pages_slider],
170
- outputs=[status_output, json_output]
171
- )
172
 
173
- gr.Markdown("""
174
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
- © 2025 محرك — Moharek GEO Platform
177
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- return demo
180
-
181
- # Main execution
182
- if __name__ == "__main__":
183
- print("✅ Creating Gradio interface...")
184
- demo = create_gradio_ui()
185
-
186
- # Mount Gradio at /gradio to avoid route conflicts
187
- print("✅ Mounting Gradio to FastAPI at /gradio...")
188
- app = gr.mount_gradio_app(fastapi_app, demo, path="/gradio", root_path=os.environ.get("SPACE_ID", ""))
189
-
190
- # Add root redirect to Gradio
191
- from fastapi.responses import RedirectResponse
192
-
193
- @app.get("/")
194
- async def root_redirect():
195
- return RedirectResponse(url="/gradio")
196
-
197
- print("✅ Starting server...")
198
- print("📍 Gradio UI: /gradio")
199
- print("📍 Portal: /app/portal.html")
200
- print("📍 Login: /app/login.html")
201
- print("📍 API: /api/*")
202
-
203
- uvicorn.run(
204
- app,
205
- host=HOST,
206
- port=PORT,
207
- log_level="info",
208
- root_path=os.environ.get("SPACE_ID", "")
209
  )
 
 
 
 
 
 
 
 
 
 
1
  """
2
  Moharek GEO Platform - Hugging Face Space
3
+ AI-Powered Generative Engine Optimization Platform
4
  """
5
 
6
  import os
7
  import sys
8
  from pathlib import Path
9
 
10
+ # Add server to path
11
  sys.path.insert(0, str(Path(__file__).parent))
12
 
13
  import gradio as gr
14
+ from fastapi import FastAPI
15
  from fastapi.staticfiles import StaticFiles
16
+ from fastapi.responses import FileResponse, HTMLResponse
17
 
18
+ # Import the main API
19
  from server.api import app as fastapi_app
20
 
21
  # Configuration
 
 
 
 
 
 
 
 
22
  frontend_path = Path(__file__).parent / "frontend"
23
+
24
+ # Mount frontend static files
25
  if frontend_path.exists():
26
+ # Mount all static assets
27
+ fastapi_app.mount("/assets", StaticFiles(directory=str(frontend_path / "assets")), name="assets")
28
 
29
+ # Serve SVG logos
30
+ @fastapi_app.get("/moharek-logo-v2.svg")
31
+ async def serve_logo_v2():
32
+ return FileResponse(str(frontend_path / "moharek-logo-v2.svg"))
33
 
34
+ @fastapi_app.get("/moharek-logo.svg")
35
+ async def serve_logo():
36
+ return FileResponse(str(frontend_path / "moharek-logo.svg"))
37
+
38
+ @fastapi_app.get("/moharek-favicon.svg")
39
+ async def serve_favicon():
40
+ return FileResponse(str(frontend_path / "moharek-favicon.svg"))
41
+
42
+ # Serve JavaScript files
43
+ @fastapi_app.get("/{filename}.js")
44
+ async def serve_js(filename: str):
45
+ file_path = frontend_path / f"{filename}.js"
46
+ if file_path.exists():
47
+ return FileResponse(str(file_path), media_type="application/javascript")
48
+ return {"ok": False, "error": "not found"}
49
 
50
+ # Serve CSS files
51
+ @fastapi_app.get("/{filename}.css")
52
+ async def serve_css(filename: str):
53
+ file_path = frontend_path / f"{filename}.css"
54
+ if file_path.exists():
55
+ return FileResponse(str(file_path), media_type="text/css")
56
+ return {"ok": False, "error": "not found"}
57
+
58
+ # Serve HTML pages
59
+ @fastapi_app.get("/{page}.html")
60
+ async def serve_page(page: str):
61
+ file_path = frontend_path / f"{page}.html"
62
+ if file_path.exists():
63
+ return FileResponse(str(file_path), media_type="text/html")
64
+ return {"ok": False, "error": "not found"}
65
+
66
+ # Serve index at root
67
+ @fastapi_app.get("/")
68
+ async def serve_index():
69
  index_file = frontend_path / "index.html"
70
  if index_file.exists():
71
+ return FileResponse(str(index_file), media_type="text/html")
72
+ return HTMLResponse(content="<h1>Moharek GEO Platform</h1><p>Frontend files not found</p>")
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  # Create Gradio interface
75
+ with gr.Blocks(
76
+ title="Moharek GEO Platform",
77
+ theme=gr.themes.Soft(primary_hue="teal", secondary_hue="green"),
78
+ css="""
79
+ .gradio-container {
80
+ background: linear-gradient(135deg, #071f21 0%, #0F4246 100%);
81
+ font-family: 'Cairo', sans-serif;
82
+ }
83
+ .gr-button-primary {
84
+ background: linear-gradient(135deg, #c8f04e, #a8d630) !important;
85
+ color: #071f21 !important;
86
+ font-weight: 900 !important;
87
+ }
88
+ """
89
+ ) as demo:
90
+
91
+ gr.Markdown("""
92
+ # 🚀 محرك — Moharek GEO Platform
93
+
94
+ ## منصة تحسين محركات البحث بالذكاء الاصطناعي
95
+
96
+ **Search Growth System** — 5 محركات متكاملة تغطي كل رحلة العميل
97
+
98
+ ---
99
+
100
+ ### 🎯 الميزات الرئيسية:
101
+
102
+ - 📈 **SEO Engine** — تحسين محركات البحث التقليدية
103
+ - 🤖 **AI Visibility Engine** — الظهور في ChatGPT و Gemini
104
+ - 🎯 **Ads Engine** — إدارة الإعلانات الذكية
105
+ - 📝 **Content Engine** — إنشاء محتوى متعدد القنوات
106
+ - ⭐ **Trust Engine** — بناء الثقة والسمعة الرقمية
107
+ """)
108
+
109
+ with gr.Row():
110
+ with gr.Column(scale=2):
111
+ gr.Markdown("### 🔍 ابدأ تحليل موقعك الآن")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
+ website_url = gr.Textbox(
114
+ label="رابط الموقع",
115
+ placeholder="https://example.com",
116
+ info="أدخل رابط موقعك للحصول على تحليل شامل"
117
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
+ org_name = gr.Textbox(
120
+ label="اسم الشركة/المؤسسة",
121
+ placeholder="اسم شركتك"
122
+ )
123
+
124
+ max_pages = gr.Slider(
125
+ minimum=10,
126
+ maximum=100,
127
+ value=50,
128
+ step=10,
129
+ label="عدد الصفحات للتحليل"
130
+ )
131
+
132
+ analyze_btn = gr.Button("🚀 ابدأ التحليل", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
+ with gr.Column(scale=1):
135
+ gr.Markdown("""
136
+ ### 📊 ماذا ستحصل؟
137
+
138
+ ✅ تحليل SEO شامل
139
+ ✅ تقييم GEO Score
140
+ ✅ استخراج الكلمات المفتاحية
141
+ ✅ تحليل المحتوى
142
+ ✅ توصيات قابلة للتنفيذ
143
+
144
+ ---
145
+
146
+ ### 🌐 الوصول الكامل
147
+
148
+ 👉 <a href="/portal.html" target="_blank">افتح لوحة التحكم</a>
149
+
150
+ 👉 <a href="/index.html" target="_blank">الصفحة الرئيسية</a>
151
+
152
+ 👉 <a href="/api/docs" target="_blank">API Documentation</a>
153
+ """)
154
+
155
+ output_status = gr.Textbox(label="حالة التحليل", interactive=False, lines=3)
156
+ output_json = gr.JSON(label="نتائج التحليل")
157
+
158
+ def analyze_website(url, name, pages):
159
+ if not url or not url.startswith('http'):
160
+ return "❌ الرجاء إدخال رابط صحيح يبدأ بـ http:// أو https://", None
161
 
162
+ try:
163
+ import requests
164
+ response = requests.post(
165
+ "http://localhost:7860/api/jobs",
166
+ json={
167
+ "url": url,
168
+ "org_name": name or "Unknown",
169
+ "org_url": url,
170
+ "max_pages": int(pages),
171
+ "runs": 1
172
+ },
173
+ timeout=30
174
+ )
175
+
176
+ if response.status_code == 200:
177
+ data = response.json()
178
+ if data.get("ok"):
179
+ job_id = data.get("job_id")
180
+ return f"✅ تم إنشاء التحليل بنجاح!\n\nJob ID: {job_id}\n\nيمكنك متابعة التقدم من لوحة التحكم", data
181
+ else:
182
+ return f"❌ خطأ: {data.get('error', 'Unknown error')}", None
183
+ else:
184
+ return f"❌ خطأ في الاتصال: {response.status_code}", None
185
+ except Exception as e:
186
+ return f"❌ حدث خطأ: {str(e)}", None
187
 
188
+ analyze_btn.click(
189
+ fn=analyze_website,
190
+ inputs=[website_url, org_name, max_pages],
191
+ outputs=[output_status, output_json]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  )
193
+
194
+ gr.Markdown("""
195
+ ---
196
+
197
+ © 2025 محرك — Moharek GEO Platform | Search Growth System
198
+ """)
199
+
200
+ # Mount Gradio app to FastAPI
201
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/")