syurein commited on
Commit
2443b6b
·
1 Parent(s): fd6583c

jinja修正

Browse files
Files changed (2) hide show
  1. LLM_package.py +103 -0
  2. app.py +14 -4
LLM_package.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google import genai
2
+ import moondream as md
3
+ import json
4
+ import os
5
+ from PIL import Image
6
+ from dotenv import load_dotenv
7
+ load_dotenv()
8
+ class MoondreamInference:
9
+ def __init__(self, api_key=None):
10
+ if api_key is None:
11
+ api_key = os.getenv('MOONDREAM_API_KEY')
12
+ self.model = md.vl(api_key=api_key)
13
+
14
+ def get_response(self, image_path, prompt):
15
+ """
16
+ COCOEvaluator は get_response を呼ぶので、
17
+ ここで Moondream の detect を内部で呼び、結果を JSON文字列で返す
18
+ """
19
+ image = Image.open(image_path)
20
+ cat = list(prompt) # prompt を直接カテゴリ名に使う
21
+ result = self.model.detect(image, list(cat)[0])
22
+ # Moondream はすでに dict なので JSON にして返す
23
+ return json.dumps(result["objects"])
24
+
25
+ def parse_response(self, resp_text):
26
+ """
27
+ get_response で返した JSON文字列をパースし、
28
+ Gemini と同じ形式の list[dict] に揃える
29
+ """
30
+
31
+ detections = json.loads(resp_text)
32
+ parsed = []
33
+ for obj in detections:
34
+ parsed.append({
35
+ "label": obj.get("label", "object"), # ない場合もあるかも
36
+ "box_2d": [
37
+ obj["y_min"], obj["x_min"],
38
+ obj["y_max"], obj["x_max"]
39
+ ]
40
+ })
41
+ print(parsed)
42
+ return parsed
43
+
44
+
45
+ class GeminiInference:
46
+ """
47
+ Gemini API 呼び出しを扱うクラス。
48
+ """
49
+ def __init__(self, api_key_source=os.getenv('GEMINI_API_KEY')):
50
+ self.api_key_source = api_key_source
51
+
52
+ def get_response(self, file_path, prompt):
53
+ """
54
+ 画像ファイルに対して Geminin API 呼び出しを行い、レスポンステキストを返す。
55
+ """
56
+ client = genai.Client(api_key=self.api_key_source)
57
+ my_file = client.files.upload(file=file_path)
58
+ response = client.models.generate_content(
59
+ model="gemini-2.0-flash",
60
+ contents=[my_file, prompt],
61
+ )
62
+ return response.text
63
+ def get_response_text(self,prompt):
64
+ client = genai.Client(api_key=self.api_key_source)
65
+ response = client.models.generate_content(
66
+ model="gemini-2.0-flash",
67
+ contents=[prompt],
68
+ )
69
+ text = response.text
70
+ return text
71
+ def parse(self, text):
72
+ """
73
+ レスポンス JSON をパース。'label' と 'box_2d'([0-1000]正規化) を取り出し、[0,1]正規化に変換して返すリスト。
74
+ """
75
+ json_str = text
76
+ if '```json' in text:
77
+ json_str = text[text.find('```json') + len('```json'):]
78
+
79
+ json_str = json_str.strip('` \n')
80
+ return json_str
81
+ def parse_response(self, text):
82
+ """
83
+ レスポンス JSON をパース。'label' と 'box_2d'([0-1000]正規化) を取り出し、[0,1]正規化に変換して返すリスト。
84
+ """
85
+ print(text)
86
+ json_str = text
87
+ if '```json' in text:
88
+ json_str = text[text.find('```json') + len('```json'):]
89
+ json_str = json_str.strip('` \n')
90
+ try:
91
+ data = json.loads(json_str)
92
+ except Exception as e:
93
+ print("JSON パースエラー:", e)
94
+ return []
95
+ if isinstance(data, dict):
96
+ data = [data]
97
+ parsed = []
98
+ for obj in data:
99
+ if 'box_2d' in obj and 'label' in obj:
100
+ coords = obj['box_2d']
101
+ norm = [c / 1000.0 for c in coords]
102
+ parsed.append({'label': obj['label'], 'box_2d': norm})
103
+ return parsed
app.py CHANGED
@@ -50,7 +50,8 @@ from ultralytics import YOLO
50
  import math
51
  import numpy as np
52
  import matplotlib.pyplot as plt
53
-
 
54
  #この下のコードは特定の領域をマスクしないタイプのコード
55
  import uuid
56
  from datetime import datetime
@@ -58,7 +59,7 @@ import torch
58
  import cv2
59
  import numpy as np
60
  from ultralytics import YOLO # YOLOv8ライブラリ
61
-
62
  import random
63
  import cv2
64
  import numpy as np
@@ -75,7 +76,7 @@ app.add_middleware(
75
  allow_headers=["*"],
76
  )
77
 
78
-
79
  HOME = "./"
80
  templates = Jinja2Templates(directory="templates")
81
  dangerarray=[10,30,90,50,80,20,40,70,100,60]#ここに各クラスターの危険度を設定しておく
@@ -224,6 +225,13 @@ def create_mask(image, x1, y1, x2, y2):
224
 
225
  import easyocr
226
 
 
 
 
 
 
 
 
227
  # 特殊な処理を行う関数
228
  def special_process_image_yolo(risk_level, image_path, point1, point2, thresholds=None):
229
  # デバイスの確認
@@ -902,5 +910,7 @@ async def mosaic_faces(reference_image: UploadFile = File(...), test_image: Uplo
902
 
903
  @app.get("/", response_class=HTMLResponse)
904
  async def read_root():
905
- return templates.TemplateResponse("index.html")
 
 
906
 
 
50
  import math
51
  import numpy as np
52
  import matplotlib.pyplot as plt
53
+ from dotenv import load_dotenv
54
+ from pathlib import Path
55
  #この下のコードは特定の領域をマスクしないタイプのコード
56
  import uuid
57
  from datetime import datetime
 
59
  import cv2
60
  import numpy as np
61
  from ultralytics import YOLO # YOLOv8ライブラリ
62
+ from fastapi.middleware.cors import CORSMiddleware, Request
63
  import random
64
  import cv2
65
  import numpy as np
 
76
  allow_headers=["*"],
77
  )
78
 
79
+ load_dotenv(dotenv_path='../.env')
80
  HOME = "./"
81
  templates = Jinja2Templates(directory="templates")
82
  dangerarray=[10,30,90,50,80,20,40,70,100,60]#ここに各クラスターの危険度を設定しておく
 
225
 
226
  import easyocr
227
 
228
+
229
+
230
+ def llm_to_process_image(risk_level, image_path, point1, point2, thresholds=None):
231
+ print('point1,point2', point1, point2)
232
+ # 画像処理のロジックをここに追加
233
+ pass
234
+
235
  # 特殊な処理を行う関数
236
  def special_process_image_yolo(risk_level, image_path, point1, point2, thresholds=None):
237
  # デバイスの確認
 
910
 
911
  @app.get("/", response_class=HTMLResponse)
912
  async def read_root():
913
+ return templates.TemplateResponse("index.html", {"request": request})
914
+
915
+
916