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') # Input question and submit print("Entering question...") await page.wait_for_selector('#userInput') await page.click('#userInput') await page.type('#userInput', question) await page.keyboard.press('Enter') # Wait for response - **IMPORTANT: REPLACE WITH CORRECT SELECTOR** print("Waiting for response element...") response_selector = '[data-testid="conversation-turn"]' # <--- CHANGE THIS! 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 # Get response 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.") # Take a screenshot (optional, for debugging) screenshot = await page.screenshot() screenshot_base64 = base64.b64encode(screenshot).decode('utf-8') return response, screenshot_base64 # Return both text and image 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) # Get text and image print("Sending answer...") # Return both answer and screenshot (for debugging) 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 # For Hugging Face Spaces, we DO NOT need to run the app with app.run(). # Hugging Face Spaces handles this automatically. The following lines # are only for local testing and should be commented out or removed # when deploying to Hugging Face. # if __name__ == '__main__': # asyncio.run(app.run(debug=True, port=5000))