in appdev_genai_googlecloud/src/genai-app-firestore/main.py [0:0]
def summarize():
event = from_http(request.headers, request.get_data())
event_id = event.get("id")
data = event.data
content_type, bucket_name, name = data["contentType"], data["bucket"], data["name"]
user_id, filename = data["name"].split("/")[0], data["name"].split("/")[1]
file_id = filename[:21]
_, ext = os.path.splitext(name)
app.logger.info(f"{event_id}: start summarizing a file: {file_id}")
# Validate uploaded_file and return the file is not a PDF or an image file
if ext.lower() not in ['.pdf', '.jpg', '.jpeg', '.png'] or content_type not in ['application/pdf', 'image/jpeg', 'image/png']:
app.logger.info(f"{event_id}: skipping summarizing a file since the file is not PDF or image format: {file_id}")
return ("the file is not pdf or image", 204)
model = GenerativeModel(model_name=LLM_MODEL)
gcs_path = f"gs://{bucket_name}/{name}"
doc_part = Part.from_uri(gcs_path, content_type)
config = GenerationConfig(
max_output_tokens=MAX_SUMMARIZATION_LENGTH + 1000, temperature=0, top_p=1, top_k=32,
)
prompt = f"""You are an AI assistant.
Summarize the contents for readers who doesn't have enough domain knowledge.
Output the result in Japanese and the result must be less than {MAX_SUMMARIZATION_LENGTH} characters.
"""
try:
doc_ref = db.collection("users").document(user_id).collection("items").document(file_id)
app.logger.info(f"{event_id}: start generating a summary for a file: {file_id}")
response = model.generate_content([doc_part, prompt], generation_config=config)
app.logger.info(f"{event_id}: finished generating a summary for a file: {file_id}")
doc_ref.update({"description": response.text})
app.logger.info(f"{event_id}: finished summarizing a file: {file_id}")
except Exception as err:
app.logger.info(f"{event_id}: failed generating a summary for a file: {file_id}")
doc_ref.update({"description": SUMMARIZATION_FAILED_MESSAGE})
app.logger.info(f"{event_id}: failed summarizing a file: {err=}, {type(err)=}")
return ("finished", 204)