File size: 3,293 Bytes
7a8ef73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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))