Created
March 20, 2025 09:03
-
-
Save k0ta0uchi/951c0c109465319583b7f4a123c18370 to your computer and use it in GitHub Desktop.
Gemini OCRサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
using System.Text.Json; | |
public class GoogleAI | |
{ | |
private readonly string _apiKey; | |
public GoogleAI(string apiKey) | |
{ | |
_apiKey = apiKey; | |
} | |
public async Task<GenerateContentResponse> GenerateContentObject(string systemInstructionText, string contentText, string base64Image, string mimeType, string modelName) | |
{ | |
var url = $"https://generativelanguage.googleapis.com/v1beta/models/{modelName}:generateContent?key={_apiKey}"; | |
var requestJson = new | |
{ | |
contents = new object[] | |
{ | |
new | |
{ | |
parts = new object[] | |
{ | |
new { text = contentText }, | |
new | |
{ | |
inlineData = new | |
{ | |
mimeType = mimeType, | |
data = base64Image | |
} | |
} | |
} | |
} | |
} | |
}; | |
var jsonString = JsonSerializer.Serialize(requestJson); | |
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); | |
using var httpClient = new HttpClient(); | |
var response = await httpClient.PostAsync(url, stringContent); | |
response.EnsureSuccessStatusCode(); | |
var responseContent = await response.Content.ReadAsStringAsync(); | |
return JsonSerializer.Deserialize<GenerateContentResponse>(responseContent); | |
} | |
public class GenerateContentResponse | |
{ | |
public Candidate[] candidates { get; set; } | |
public class Candidate | |
{ | |
public Content content { get; set; } | |
public SafetyRating[] safetyRatings { get; set; } | |
} | |
public class Content | |
{ | |
public Part[] parts { get; set; } | |
} | |
public class Part | |
{ | |
public string text { get; set; } | |
} | |
public class SafetyRating | |
{ | |
public string category { get; set; } | |
public string probability { get; set; } | |
} | |
} | |
private const string ApiKey = "YOUR-API-KEY"; | |
private const string SystemInstructionText = @" | |
あなたは画像認識とOCR(光学文字認識)の専門家です。与えられた画像から文字を抽出し、その構造を保ったままMarkdown形式に変換する任務があります。 | |
以下は、処理する必要がある画像から抽出されたMarkdownです: | |
<markdown> | |
{{markdown}} | |
</markdown> | |
このタスクを実行する際は、以下の手順に従ってください: | |
1. 画像全体を分析し、テキスト、見出し、リスト、表などの構造要素を識別します。 | |
2. 識別された各要素をMarkdown形式に変換します。その際、元の画像の構造やレイアウトをできるだけ忠実に再現してください。 | |
3. 変換されたMarkdownを確認し、元の画像の構造が正確に反映されているか確認します。 | |
4. 必要に応じて、Markdown形式を微調整して、より正確に元の画像の構造を表現します。 | |
最終的な出力を提供する前に、<変換プロセス>タグ内で変換プロセスについて詳しく説明してください。以下の点を含めて説明してください: | |
- Markdownから識別された主な構造要素をリストアップし、分類してください。 | |
- 各要素タイプをMarkdown構文にどのように変換するかを説明してください。 | |
- 元のレイアウトを保持する上で考えられる課題を特定してください。 | |
変換された最終的なMarkdownは<変換済みMarkdown>タグ内に記述してください。 | |
それでは、与えられた画像のMarkdown変換を開始してください。 | |
"; | |
static async Task Main(string[] args) | |
{ | |
if (string.IsNullOrEmpty(ApiKey)) | |
{ | |
Console.WriteLine("APIキーが設定されていません。"); | |
return; | |
} | |
Console.Write("画像ファイルのパスを入力してください: "); | |
var imgPath = Console.ReadLine(); | |
var mimeType = MimeTypes.GetMimeType(Path.GetExtension(imgPath)); | |
try | |
{ | |
var base64Image = Convert.ToBase64String(File.ReadAllBytes(imgPath)); | |
var genAi = new GoogleAI(ApiKey); | |
var response = await genAi.GenerateContentObject(SystemInstructionText, "", base64Image, mimeType, "gemini-2.0-pro-exp-02-05"); | |
Console.WriteLine("\n応答: " + response.candidates[0].content.parts[0].text); | |
} | |
catch (HttpRequestException ex) | |
{ | |
Console.WriteLine($"HTTPリクエストでの例外が発生しました: {ex.Message}"); | |
if (ex.InnerException != null) | |
{ | |
Console.WriteLine($"Inner Exception: {ex.InnerException.Message}"); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"例外が発生しました: {ex.Message}"); | |
} | |
} | |
} | |
public static class MimeTypes | |
{ | |
private static readonly Dictionary<string, string> _mimeTypes = new Dictionary<string, string> | |
{ | |
{ ".jpg", "image/jpeg" }, | |
{ ".jpeg", "image/jpeg" }, | |
{ ".png", "image/png" }, | |
{ ".gif", "image/gif" }, | |
// Add more MIME types as needed | |
}; | |
public static string GetMimeType(string extension) | |
{ | |
if (_mimeTypes.TryGetValue(extension.ToLower(), out var mimeType)) | |
{ | |
return mimeType; | |
} | |
throw new ArgumentException($"Unknown MIME type for extension: {extension}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment