|
| 1 | +package com.google.ai.sample.util |
| 2 | + |
| 3 | +import android.util.Log |
| 4 | +import java.util.regex.Pattern |
| 5 | + |
| 6 | +/** |
| 7 | + * Utility class for parsing commands from AI responses |
| 8 | + */ |
| 9 | +object CommandParser { |
| 10 | + private const val TAG = "CommandParser" |
| 11 | + |
| 12 | + // Command patterns |
| 13 | + private val CLICK_BUTTON_PATTERN = Pattern.compile("clickOnButton\\(\\s*\"([^\"]+)\"\\s*\\)") |
| 14 | + private val TAP_COORDINATES_PATTERN = Pattern.compile("tapAtCoordinates\\(\\s*([0-9.]+)\\s*,\\s*([0-9.]+)\\s*\\)") |
| 15 | + |
| 16 | + /** |
| 17 | + * Parse commands from AI response text |
| 18 | + * @param text The AI response text to parse |
| 19 | + * @return List of parsed commands |
| 20 | + */ |
| 21 | + fun parseCommands(text: String): List<Command> { |
| 22 | + val commands = mutableListOf<Command>() |
| 23 | + |
| 24 | + // Find clickOnButton commands |
| 25 | + val clickMatcher = CLICK_BUTTON_PATTERN.matcher(text) |
| 26 | + while (clickMatcher.find()) { |
| 27 | + val buttonText = clickMatcher.group(1) |
| 28 | + if (buttonText != null) { |
| 29 | + Log.d(TAG, "Found clickOnButton command: $buttonText") |
| 30 | + commands.add(Command.ClickButton(buttonText)) |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Find tapAtCoordinates commands |
| 35 | + val tapMatcher = TAP_COORDINATES_PATTERN.matcher(text) |
| 36 | + while (tapMatcher.find()) { |
| 37 | + try { |
| 38 | + val x = tapMatcher.group(1)?.toFloat() |
| 39 | + val y = tapMatcher.group(2)?.toFloat() |
| 40 | + if (x != null && y != null) { |
| 41 | + Log.d(TAG, "Found tapAtCoordinates command: $x, $y") |
| 42 | + commands.add(Command.TapCoordinates(x, y)) |
| 43 | + } |
| 44 | + } catch (e: NumberFormatException) { |
| 45 | + Log.e(TAG, "Error parsing coordinates: ${e.message}") |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return commands |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Sealed class representing different types of commands |
| 55 | + */ |
| 56 | +sealed class Command { |
| 57 | + /** |
| 58 | + * Command to click a button with specific text |
| 59 | + */ |
| 60 | + data class ClickButton(val buttonText: String) : Command() |
| 61 | + |
| 62 | + /** |
| 63 | + * Command to tap at specific coordinates |
| 64 | + */ |
| 65 | + data class TapCoordinates(val x: Float, val y: Float) : Command() |
| 66 | +} |
0 commit comments