You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SafeLlavaImageEmbedHandle.cs 2.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. namespace LLama.Native
  4. {
  5. /// <summary>
  6. /// A Reference to a llava Image Embed handle
  7. /// </summary>
  8. public sealed class SafeLlavaImageEmbedHandle
  9. : SafeLLamaHandleBase
  10. {
  11. /// <summary>
  12. /// Create an image embed from an image file
  13. /// </summary>
  14. /// <param name="ctxLlava"></param>
  15. /// <param name="ctxLlama"></param>
  16. /// <param name="image">Path to the image file. Supported formats:
  17. /// <list type="bullet">
  18. /// <item>JPG</item>
  19. /// <item>PNG</item>
  20. /// <item>BMP</item>
  21. /// <item>TGA</item>
  22. /// </list>
  23. /// </param>
  24. /// <returns></returns>
  25. /// <exception cref="InvalidOperationException"></exception>
  26. public static SafeLlavaImageEmbedHandle CreateFromFileName( SafeLlavaModelHandle ctxLlava, LLamaContext ctxLlama, string image )
  27. {
  28. // Try to open the image file, this will check:
  29. // - File exists (automatically throws FileNotFoundException)
  30. // - File is readable (explicit check)
  31. // This provides better error messages that llama.cpp, which would throw an access violation exception in both cases.
  32. using (var fs = new FileStream(image, FileMode.Open))
  33. if (!fs.CanRead)
  34. throw new InvalidOperationException($"Llava image file '{image}' is not readable");
  35. return NativeApi.llava_image_embed_make_with_filename(ctxLlava, (int) ctxLlama.BatchThreads, image);
  36. }
  37. /// <summary>
  38. /// Create an image embed from the bytes of an image.
  39. /// </summary>
  40. /// <param name="ctxLlava"></param>
  41. /// <param name="ctxLlama"></param>
  42. /// <param name="image">Image bytes. Supported formats:
  43. /// <list type="bullet">
  44. /// <item>JPG</item>
  45. /// <item>PNG</item>
  46. /// <item>BMP</item>
  47. /// <item>TGA</item>
  48. /// </list>
  49. /// </param>
  50. /// <returns></returns>
  51. public static SafeLlavaImageEmbedHandle CreateFromMemory( SafeLlavaModelHandle ctxLlava, LLamaContext ctxLlama, byte[] image )
  52. {
  53. return NativeApi.llava_image_embed_make_with_bytes(ctxLlava, (int) ctxLlama.BatchThreads, image, image.Length);
  54. }
  55. /// <inheritdoc />
  56. protected override bool ReleaseHandle()
  57. {
  58. NativeApi.llava_image_embed_free(DangerousGetHandle());
  59. SetHandle(IntPtr.Zero);
  60. return true;
  61. }
  62. }
  63. }