Spaces:
Running
Running
Download backend/app/api/landing.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 5.76 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/landing.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/landing.py
-
curl -L -o landing.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/landing.py
5.76 kB
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlmodel import select | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from pydantic import BaseModel | |
| from typing import List, Optional | |
| from app.core.database import get_session | |
| from app.models.landing import LandingConfig | |
| from app.schemas.landing import LandingConfigResponse, LandingConfigUpdate | |
| from app.api.deps import get_current_user | |
| from app.models.user import User, UserRole | |
| from app.services.gemini_client import GoogleGeminiClient | |
| router = APIRouter() | |
| # Demo chat models | |
| class DemoChatMessage(BaseModel): | |
| role: str # "user" or "bot" | |
| text: str | |
| class DemoChatRequest(BaseModel): | |
| message: str | |
| history: Optional[List[DemoChatMessage]] = [] | |
| class DemoChatResponse(BaseModel): | |
| reply: str | |
| success: bool = True | |
| # Demo chat system prompt | |
| DEMO_SYSTEM_PROMPT = """Ты — AI-продавец MicroFunnel. Твоя задача — отвечать на вопросы потенциальных клиентов о платформе MicroFunnel. | |
| ## О ПЛАТФОРМЕ MICROFUNNEL: | |
| MicroFunnel — это AI-платформа для автоматизации продаж в мессенджерах (WhatsApp, Telegram, Instagram). | |
| ### КЛЮЧЕВЫЕ ФУНКЦИИ: | |
| 1. **Каталог товаров** — AI знает весь ваш ассортимент, цены и наличие | |
| 2. **Саммари диалога** — автоматическое резюме из 11 пунктов | |
| 3. **DISC-психология** — адаптация тона под психотип клиента | |
| 4. **Встроенный календарь** — бронирование встреч прямо в чате | |
| 5. **Автодожим** — ведение клиента до оплаты | |
| 6. **Работа 24/7** — мгновенные ответы в любое время | |
| 7. **Мультиязычность** — 95 языков | |
| 8. **База знаний** — загрузка PDF/TXT для обучения бота | |
| ### ТАРИФЫ: | |
| - Start: $69/мес (500 диалогов) | |
| - Growth: $139/мес (1500 диалогов) — популярный | |
| - Unlimited: $349/мес (безлимит) | |
| При оплате за год — скидка 30%. | |
| ### ПРАВИЛА ОБЩЕНИЯ: | |
| - Отвечай КРАТКО (2-3 предложения) | |
| - Будь ДРУЖЕЛЮБНЫМ и ПРОФЕССИОНАЛЬНЫМ | |
| - Используй эмодзи умеренно | |
| - Если спрашивают о цене — предложи записаться на демо | |
| - Отвечай ТОЛЬКО на русском языке | |
| """ | |
| async def get_landing_config(session: AsyncSession = Depends(get_session)): | |
| """ | |
| Get landing page configuration. Public endpoint. | |
| Creates default config if none exists. | |
| """ | |
| result = await session.execute(select(LandingConfig)) | |
| config = result.scalars().first() | |
| if not config: | |
| # Create default config | |
| config = LandingConfig( | |
| trust_logos=['TechCorp', 'StartupHub', 'GrowthLab', 'SalesForce', 'Microsoft'], | |
| hero_title='ПРОДАВАЙТЕ УМНЕЕ.', | |
| hero_subtitle='Ваш AI-двигатель продаж.', | |
| show_chat_demo=True, | |
| show_pricing=True | |
| ) | |
| session.add(config) | |
| await session.commit() | |
| await session.refresh(config) | |
| return config | |
| async def update_landing_config( | |
| config_in: LandingConfigUpdate, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_session) | |
| ): | |
| """ | |
| Update landing page configuration. Only for admins/owners. | |
| """ | |
| # Allow OWNER or superuser | |
| if current_user.role != UserRole.OWNER and not current_user.is_superuser: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Not authorized to edit landing settings" | |
| ) | |
| result = await session.execute(select(LandingConfig)) | |
| config = result.scalars().first() | |
| if not config: | |
| config = LandingConfig() | |
| # Update fields | |
| config_data = config_in.model_dump(exclude_unset=True) | |
| for key, value in config_data.items(): | |
| setattr(config, key, value) | |
| session.add(config) | |
| await session.commit() | |
| await session.refresh(config) | |
| return config | |
| async def demo_chat(request: DemoChatRequest): | |
| """ | |
| Public endpoint for demo AI chat on landing page. | |
| Uses Gemini API directly with MicroFunnel context. | |
| """ | |
| try: | |
| # Initialize Gemini client | |
| gemini = GoogleGeminiClient() | |
| # Format chat history for Gemini | |
| chat_history = [] | |
| for msg in request.history[-10:]: # Last 10 messages only | |
| role = "user" if msg.role == "user" else "model" | |
| chat_history.append({"role": role, "content": msg.text}) | |
| # Generate response | |
| response = await gemini.generate_response( | |
| prompt=request.message, | |
| system_instruction=DEMO_SYSTEM_PROMPT, | |
| context=chat_history | |
| ) | |
| return DemoChatResponse(reply=response, success=True) | |
| except Exception as e: | |
| print(f"Demo chat error: {e}") | |
| # Fallback response if AI fails | |
| return DemoChatResponse( | |
| reply="Извините, сейчас высокая нагрузка. Попробуйте через минуту или запишитесь на демо! 🚀", | |
| success=False | |
| ) | |