當前位置: 妍妍網 > 碼農

使用谷歌 Gemini 大模型推理辨識驗證碼

2024-02-18碼農

在開發爬蟲過程中,有些網站需要驗證碼透過後才能進入網頁,目的很簡單,就是區分人類存取和機器爬蟲。驗證碼問題看似簡單,但要做到高準確率卻並不容易。

在大模型的浪潮中,最受歡迎的莫過於 Gemini 1.5 和 OpenAI Sora,Gemini 的優勢在於 免費的 API 和處理超長上下文的能力 ,其出色的圖片辨識效果贏得了使用者的青睞。無論是細膩的紋理還是復雜的場景,Gemini 都能準確捕捉並解讀其中的資訊。

結合上述業務邏輯, Gemini 可以提供常見圖片驗證碼的辨識能力,並且能夠對幹擾線等進行推理和捕捉,對復雜的數學計算等直接進行推理並輸出結果,這對驗證碼辨識具有很大的幫助。

添加依賴

基於 Gemini RestAPI [1] 開發的 Spring Boot Starter

<dependency>
<groupId>io.springboot.plugin</groupId>
<artifactId>gemini-spring-boot3-starter</artifactId>
<version>1.0.0</version>
</dependency>

配置 gemini 相關參數

  • 目前可以直接申請的 1.0 版本 申請 API Key [2] ,最新釋出的超長上下文 1.5 版本,需要加入 waitlist 等待

  • gemini:
    api-key:key
    proxy-host:ip
    proxy-port:port

    文本模型測試

    @Autowired
    private GeminiClient client;
    @Test
    voidgenerate(){
    // 文本格式化提示詞
    String prompt = """
    As a writing improvement assistant, your task is to improve the spelling, grammar, clarity, concision,
    and overall readability of the text provided, while breaking down long sentences, reducing repetition,
    and providing suggestions for improvement. Please provide only the corrected Chinese version of the text
    and avoid including explanations. Please begin by editing the following text:
    "
    "";
    Generate.Request request = Generate.creatTextChart(prompt + """
    透過此技術,前端可以客製任何數據、任何結構。後端接收到請求再也不用寫 Java controller 各類介面、實體程式碼,可直接操作資料庫獲取目標結果
    "
    ""
    );
    Generate.Response response = client.generate(request);
    String answer = Generate.toAnswer(response);
    System.out.println(answer);
    }

    輸出最佳化後文本:

    透過本技術,前端可以客製任何數據、任何結構。後端接收到請求無需再編寫 Java controller、實體程式碼等介面,可直接操作資料庫獲取目標結果

    圖片模型測試

    獲取驗證碼圖片原始文本

    @Test
    voidgenerateVision()throws IOException {
    String prompt = """
    I will provide you with an image CAPTCHA, please recognize the content inside the CAPTCHA and output the text
    "
    "";
    Generate.Request request = Generate.creatImageChart(prompt, new File("/Users/lengleng/Downloads/1.png"));
    Generate.Response response = client.generate(request);
    String answer = Generate.toAnswer(response);
    System.out.println(answer);
    }

    9+8=?

    獲取驗證碼圖片計算結果

    I will provide you with an image CAPTCHA. Please recognize the content inside the CAPTCHA and output the text
    . If the text is a mathematical calculation, please directly output the result

    總結

    基於大型模型的圖片辨識和推理技術,能夠極大地幫助驗證碼辨識,在後續的業務場景中,能夠顯著減少人工參與,提高效率。

    作為網站維護者,傳統的增加驗證碼噪點、變形、重疊、不同顏色、扭曲等方式來增加辨識難度的做法已經不再適用。建議盡快升級至行為驗證碼或其他更安全的認證方式。

    參考資料

    [1]

    Gemini RestAPI: https://ai.google.dev/tutorials/rest_quickstart

    [2]

    申請 API Key: https://aistudio.google.com/app/apikey