|
from flask import Flask, request, jsonify, Response |
|
import asyncio |
|
from playwright.async_api import async_playwright |
|
import base64 |
|
|
|
app = Flask(__name__) |
|
|
|
async def ask_copilot(question): |
|
print("Launching browser...") |
|
try: |
|
async with async_playwright() as p: |
|
browser = await p.chromium.launch(headless=True) |
|
print("Browser launched successfully.") |
|
page = await browser.new_page() |
|
await page.set_viewport_size({"width": 750, "height": 915}) |
|
print("Navigating to Copilot...") |
|
await page.goto('https://copilot.microsoft.com/', wait_until='networkidle') |
|
|
|
|
|
print("Entering question...") |
|
await page.wait_for_selector('#userInput') |
|
await page.click('#userInput') |
|
await page.type('#userInput', question) |
|
await page.keyboard.press('Enter') |
|
|
|
|
|
print("Waiting for response element...") |
|
response_selector = '[data-testid="conversation-turn"]' |
|
try: |
|
await page.wait_for_selector(response_selector, timeout=60000) |
|
except Exception as e: |
|
print(f"Timeout waiting for selector: {e}") |
|
await browser.close() |
|
raise |
|
|
|
|
|
print("Retrieving response...") |
|
response = await page.evaluate(f'(selector) => {{ const element = document.querySelector(selector); return element ? element.innerText : "Brak odpowiedzi"; }}', response_selector) |
|
print("Response retrieved.") |
|
|
|
|
|
screenshot = await page.screenshot() |
|
screenshot_base64 = base64.b64encode(screenshot).decode('utf-8') |
|
|
|
|
|
return response, screenshot_base64 |
|
|
|
except Exception as e: |
|
print(f"Error within ask_copilot: {e}") |
|
print(f"Stack trace: {e.__traceback__}") |
|
raise |
|
|
|
finally: |
|
if 'browser' in locals() and browser: |
|
print("Closing browser...") |
|
await browser.close() |
|
print("Browser closed.") |
|
|
|
|
|
@app.route('/api/ask', methods=['POST']) |
|
async def ask_route(): |
|
if not request.json or 'question' not in request.json: |
|
return jsonify({'error': 'Brak pytania'}), 400 |
|
|
|
question = request.json['question'] |
|
print(f"Received question: {question}") |
|
|
|
try: |
|
answer, screenshot_base64 = await ask_copilot(question) |
|
print("Sending answer...") |
|
|
|
return jsonify({'answer': answer, 'screenshot': screenshot_base64}) |
|
except Exception as e: |
|
print(f"Error in /api/ask: {e}") |
|
return jsonify({'error': 'Błąd podczas uzyskiwania odpowiedzi', 'details': str(e)}), 500 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|