Spaces:
Runtime error
Runtime error
File size: 5,578 Bytes
c394ef4 7544e55 c79fcf6 c394ef4 02fba21 c394ef4 74987e5 94514dd e147e44 02fba21 c394ef4 59fb6b1 02fba21 c394ef4 7544e55 c394ef4 7544e55 02fba21 c394ef4 7544e55 c394ef4 02fba21 ef45551 c394ef4 165918e 1894dd1 2939020 3fc402e e06ab8d 82bedaf b622537 82bedaf d449062 82bedaf c394ef4 6631389 c394ef4 6631389 74fdd11 94514dd e76bd3a 94514dd 23927be 94514dd 174750f cde9c1b 8268fa7 cde9c1b cb54091 6631389 cd18147 46fabd3 02fba21 c394ef4 02fba21 c394ef4 74987e5 c394ef4 08d1b40 74987e5 6631389 74987e5 6631389 74987e5 6631389 c394ef4 27d3356 74987e5 edc5780 cde9c1b d449062 edc5780 d449062 edc5780 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | from fastapi import FastAPI, HTTPException, Request, BackgroundTasks, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from httpx import Timeout
import httpx
import logging
import firebase_admin
from firebase_admin import credentials, firestore
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from io import BytesIO
import google.generativeai as genai
import os
import requests
# Initialize FastAPI
app = FastAPI()
# Allow all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Application starting up")
# Timeout configuration
request_timeout = Timeout(1000.0, connect=600.0)
# Gemini model configuration
# Load Firebase configuration from a file
with open('/app/secrets/gemini_key.txt', 'r') as f:
api_key = f.read()
genai.configure(api_key=api_key)
# Create the model
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "application/json",
}
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
# safety_settings = Adjust safety settings
# See https://ai.google.dev/gemini-api/docs/safety-settings
)
@app.post("/upload-pdf")
async def upload_drive_document(request: Request):
# Parse JSON payload
data = await request.json()
file_id = data.get("file_id")
"""
Endpoint to upload a document from Google Drive to Gemini
"""
try:
# Download file from Google Drive
file_content, mime_type = download_file_from_drive(file_id)
temp_file_path = "/tmp/downloaded_file.pdf"
with open(temp_file_path, "wb") as f:
f.write(file_content.getbuffer())
# Log the temporary file path
logging.info(f"File saved to {temp_file_path}")
# 2024-08-09 07:06:19,925 - INFO - Response is genai.File({
# 'name': 'files/gf1gtp9zvk54',
# 'display_name': 'testing',
# 'mime_type': 'application/pdf',
# 'sha256_hash': 'NDllZjNlMTE2ODQ1YjMxMGIxYmRiMTA3N2FhYzc3YWRiYjAxMjExZmEwZThkMmNiMzJkMjAwMjY2NDg1OGY1ZA==',
# 'size_bytes': '1725728',
# 'state': 'ACTIVE',
# 'uri': 'https://generativelanguage.googleapis.com/v1beta/files/gf1gtp9zvk54',
# 'create_time': '2024-08-09T07:06:19.639959Z',
# 'expiration_time': '2024-08-11T07:06:19.590668644Z',
# 'update_time': '2024-08-09T07:06:19.639959Z'})
# Use the file path if needed
# For example, upload to Gemini using the file path:
response = genai.upload_file(path=temp_file_path, display_name="testing")
# Clean up: remove the temporary file after processing
os.remove(temp_file_path)
logging.info(f"Response is {response}")
# title must be lower case and no -
# Generate content using the model
ai_response = model.generate_content(
["Provide answer sheet with the following property: {\"answer_sheet\": [{\"question_number\": \"1\", \"correct_answer\": \"B\"}]", response]
)
genai.delete_file(response.name)
return {"status": "success", "gemini_response": ai_response.text}
except Exception as e:
logging.error(f"Error uploading document: {e}")
raise HTTPException(status_code=500, detail="Failed to upload document")
def download_file_from_drive(file_id: str) -> (BytesIO, str):
"""
Downloads a file from Google Drive using the file ID
and returns a BytesIO stream and the MIME type.
"""
try:
# URL for downloading the file from Google Drive
url = f"https://drive.google.com/uc?export=download&id={file_id}"
# Send a GET request to the URL
response = requests.get(url, stream=True)
# Check if the request was successful
if response.status_code == 200:
# Create a BytesIO object from the response content
file_io = BytesIO(response.content)
# Get the MIME type of the file from the response headers
mime_type = response.headers.get('Content-Type', 'application/octet-stream')
return file_io, mime_type
else:
raise HTTPException(status_code=500, detail=f"Failed to download file, status code: {response.status_code}")
except Exception as e:
logging.error(f"Error downloading file from Drive: {e}")
raise HTTPException(status_code=500, detail="Failed to download file from Drive")
@app.post("/test")
async def test():
"""
Endpoint to send a URL to the Gemini model and receive a summary
"""
try:
# Create a GenerativeModel instance
model = genai.GenerativeModel(model_name="models/gemini-1.5-flash")
# title must be lower case and no -
file = genai.get_file(name="files/gf1gtp9zvk54")
# Generate content using the model
response = model.generate_content(
["Provide answers to the exam questions.", file]
)
logging.info(response)
# Return the generated text
return {"status": "success", "generated_text": response.text}
except Exception as e:
logging.error(f"Error generating content: {e}")
raise HTTPException(status_code=500, detail="Failed to generate content") |