m8chaa commited on
Commit
3fe77e9
β€’
1 Parent(s): 27cc9ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -60
app.py CHANGED
@@ -16,7 +16,10 @@ from typing import List, Optional, Dict
16
  from google.oauth2 import service_account
17
  from googleapiclient.discovery import build
18
 
 
19
  import google.generativeai as genai
 
 
20
 
21
  # start application
22
  app = FastAPI()
@@ -129,71 +132,84 @@ def convert_dicts_to_list(dicts: List[Dict], headers: List[str], add_link: bool
129
  rows.append(row)
130
  # print(rows)
131
  return rows
132
-
133
- async def request_gpt4o_completion(image_id: str, user_credit: int):
134
- openai_url = "https://api.openai.com/v1/chat/completions"
135
- headers = {"Authorization": f"Bearer {OPENAI_KEY}", "Content-Type": "application/json"}
136
- image_url = f"https://drive.usercontent.google.com/u/0/uc?id={image_id}&export=download"
137
- body = {
138
- "model": "gpt-4o-mini",
139
- "response_format": { "type": "json_object" },
140
- "messages": [
141
- {
142
- "role": "user",
143
- "content": [
144
- {
145
- "type": "text",
146
- "text": f'''
147
- μ•„λž˜μ˜ μˆœμ„œλŒ€λ‘œ μ‹€ν–‰ν•΄μ£Όμ„Έμš”:
148
- 1. {image_url} 이 λ§ν¬μ—μ„œ 파일 λ‹€μš΄λ‘œλ“œκ°€ μ™„λ£Œλ  λ•ŒκΉŒμ§€ κΈ°λ‹€λ¦¬μ„Έμš”.
149
- 2. μ΄λ―Έμ§€μ˜ λͺ¨λ“  영수증과 λͺ…함을 μ‹λ³„ν•˜κ³ , 각각의 정보λ₯Ό μΆ”μΆœν•˜μ„Έμš”.
150
- 3. μž‘μ„±ν•  λ•Œ 영수증과 λͺ…함 개수의 합이 {user_credit}을 λ„˜μ§€ μ•Šλ„λ‘ ν•˜μ„Έμš”.
151
- 4. μΆ”μΆœν•œ 정보λ₯Ό {receipt_sheet_headers}λž€μ΄ μžˆλŠ” 영수증 μ‹œνŠΈ λ˜λŠ” {business_card_sheet_headers}λž€μ΄ μžˆλŠ” λͺ…함 μ‹œνŠΈμ— 넣을 수 μžˆλ„λ‘ JSON으둜 μ •λ¦¬ν•˜μ„Έμš”.
152
- json.receipts.forEach() λ˜λŠ” json.busi_cards.forEach()
153
- (item) => insert row where header field is item.[fieldName]
154
- '''
155
- },
156
- {
157
- "type": "image_url",
158
- "image_url": {
159
- "url": image_url,
160
- "detail": "high"
161
- }
162
- }
163
- ]
164
- }
165
- ],
166
- "max_tokens": 4096
167
- }
168
 
169
- logging.info(f"Request URL: {openai_url}")
170
- logging.info(f"Request Headers: {headers}")
171
- logging.info(f"Request Body: {json.dumps(body, indent=2)}")
172
 
 
173
  try:
174
- async with httpx.AsyncClient(follow_redirects=True, timeout=300.0) as client:
175
- response = await client.post(openai_url, headers=headers, json=body)
176
- response.raise_for_status() # Raise an error for bad status codes
177
- except httpx.RequestError as exc:
178
- logging.error(f"An error occurred while requesting {exc.request.url!r}.")
179
- logging.error(f"Exception: {str(exc)}")
180
- return None
181
- except httpx.HTTPStatusError as exc:
182
- logging.error(f"HTTP error occurred: {str(exc)}")
183
- logging.error(f"Response: {exc.response.text}")
184
- return None
 
 
 
185
 
186
- logging.info(f"Response Status Code: {response.status_code}")
187
- logging.info(f"Response Body: {response.text}")
188
 
189
- completion = response.json()
190
- if 'choices' in completion and len(completion['choices']) > 0:
191
- message_content = completion['choices'][0]['message']['content']
192
- print(message_content)
193
- return message_content
194
- else:
195
- print("No response received")
196
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
  async def move_file_to_folder(file_id, current_parents, new_parents):
199
  try:
 
16
  from google.oauth2 import service_account
17
  from googleapiclient.discovery import build
18
 
19
+ from io import BytesIO
20
  import google.generativeai as genai
21
+ import os
22
+ import requests
23
 
24
  # start application
25
  app = FastAPI()
 
132
  rows.append(row)
133
  # print(rows)
134
  return rows
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
 
 
 
136
 
137
+ async def request_gpt4o_completion(image_id: str, user_credit: int):
138
  try:
139
+ # Download file from Google Drive
140
+ file_content, mime_type = download_file_from_drive(image_id)
141
+
142
+ temp_file_path = "/tmp/downloaded_file.pdf"
143
+ with open(temp_file_path, "wb") as f:
144
+ f.write(file_content.getbuffer())
145
+
146
+ # Log the temporary file path
147
+ logging.info(f"File saved to {temp_file_path}")
148
+
149
+ genai_file = genai.upload_file(path=temp_file_path, display_name="yungsoogi")
150
+
151
+ # Clean up: remove the temporary file after processing
152
+ os.remove(temp_file_path)
153
 
 
 
154
 
155
+ prompt = f'''
156
+ μ•„λž˜μ˜ μˆœμ„œλŒ€λ‘œ μ‹€ν–‰ν•΄μ£Όμ„Έμš”:
157
+ 1. {image_url} 이 λ§ν¬μ—μ„œ 파일 λ‹€μš΄λ‘œλ“œκ°€ μ™„λ£Œλ  λ•ŒκΉŒμ§€ κΈ°λ‹€λ¦¬μ„Έμš”.
158
+ 2. μ΄λ―Έμ§€μ˜ λͺ¨λ“  영수증과 λͺ…함을 μ‹λ³„ν•˜κ³ , 각각의 정보λ₯Ό μΆ”μΆœν•˜μ„Έμš”.
159
+ 3. μž‘μ„±ν•  λ•Œ 영수증과 λͺ…함 개수의 합이 {user_credit}을 λ„˜μ§€ μ•Šλ„λ‘ ν•˜μ„Έμš”.
160
+ 4. μΆ”μΆœν•œ 정보λ₯Ό {receipt_sheet_headers}λž€μ΄ μžˆλŠ” 영수증 μ‹œνŠΈ λ˜λŠ” {business_card_sheet_headers}λž€μ΄ μžˆλŠ” λͺ…함 μ‹œνŠΈμ— 넣을 수 μžˆλ„λ‘ JSON으둜 μ •λ¦¬ν•˜μ„Έμš”.
161
+ json.receipts.forEach() λ˜λŠ” json.busi_cards.forEach()
162
+ (item) => insert row where header field is item.[fieldName]
163
+ '''
164
+
165
+
166
+ # Generate content using the model
167
+ ai_response = model.generate_content(
168
+ [prompt, genai_file]
169
+ )
170
+
171
+ genai.delete_file(response.name)
172
+
173
+ logging.info(f"Response Body: {ai_response}")
174
+
175
+ return None
176
+
177
+ # if 'choices' in completion and len(completion['choices']) > 0:
178
+ # message_content = completion['choices'][0]['message']['content']
179
+ # print(message_content)
180
+ # return message_content
181
+ # else:
182
+ # print("No response received")
183
+ # return None
184
+
185
+ def download_file_from_drive(file_id: str) -> (BytesIO, str):
186
+ """
187
+ Downloads a file from Google Drive using the file ID
188
+ and returns a BytesIO stream and the MIME type.
189
+ """
190
+ try:
191
+ # URL for downloading the file from Google Drive
192
+ url = f"https://drive.google.com/uc?export=download&id={file_id}"
193
+
194
+ # Send a GET request to the URL
195
+ response = requests.get(url, stream=True)
196
+
197
+ # Check if the request was successful
198
+ if response.status_code == 200:
199
+ # Create a BytesIO object from the response content
200
+ file_io = BytesIO(response.content)
201
+
202
+ # Get the MIME type of the file from the response headers
203
+ mime_type = response.headers.get('Content-Type', 'application/octet-stream')
204
+
205
+ return file_io, mime_type
206
+ else:
207
+ raise HTTPException(status_code=500, detail=f"Failed to download file, status code: {response.status_code}")
208
+
209
+ except Exception as e:
210
+ logging.error(f"Error downloading file from Drive: {e}")
211
+ raise HTTPException(status_code=500, detail="Failed to download file from Drive")
212
+
213
 
214
  async def move_file_to_folder(file_id, current_parents, new_parents):
215
  try: