글 초안 생성 API 구현

목표

  • 사용자가 선택한 주제 + 카테고리를 받아
  • Gemini API로 150단어 내외의 글 초안 생성
  • 카테고리에 따라 어조를 다르게 출력

카테고리별 스타일 가이드

  • 블로그 게시물 → 친근하고 흥미로운 어조
  • 짧은 보고서 → 객관적이고 사실적인 어조
  • 아이디어 노트 → 간결하고 메모 형식
  • 시(詩) → 문학적이고 감성적인 어조

코드 작성

app.py글 생성 API를 추가합니다.

import os
import google.generativeai as genai
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename

# Flask 초기화
app = Flask(__name__)

# 업로드 폴더
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Gemini API 설정
genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
model = genai.GenerativeModel("gemini-1.5-pro")

# 허용 확장자
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 홈
@app.route('/')
def home():
    return jsonify({"message": "IdeaSnap Backend is running!"})

# 글 초안 생성 API
@app.route('/api/generate-text', methods=['POST'])
def generate_text():
    data = request.json
    topic = data.get("topic")
    category = data.get("category")
    keywords = data.get("keywords", [])

    if not topic or not category:
        return jsonify({"error": "Topic and category are required"}), 400

    # 카테고리별 추가 지시어
    styles = {
        "블로그 게시물": "친근하고 흥미로운 어조로 작성",
        "짧은 보고서": "객관적이고 사실적인 어조로 작성",
        "아이디어 노트": "간결하고 메모 형식으로 작성",
        "시": "문학적이고 감성적인 어조로 작성"
    }
    style_instruction = styles.get(category, "자연스럽게 작성")

    # 프롬프트 구성
    prompt = f"""
    주제: "{topic}"
    카테고리: "{category}"
    키워드: {", ".join(keywords)}
    
    위 정보를 바탕으로 약 150단어 내외의 글을 작성해주세요.
    스타일: {style_instruction}
    """

    # Gemini API 호출
    response = model.generate_content(prompt)

    return jsonify({
        "topic": topic,
        "category": category,
        "generated_text": response.text
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

프로젝트 구조 (지금까지)

ideasnap-backend/
 ├─ uploads/              # 업로드된 이미지 저장
 ├─ venv/                 # 가상환경
 ├─ app.py                # Flask 서버 메인 파일
 └─ sample.jpg

테스트 방법

요청 JSON 파일(request.json) 만들기

{
  "topic": "자연이 주는 위로",
  "category": "블로그 게시물",
  "keywords": ["자연", "꽃", "평화"]
}

curl 실행

curl -X POST http://127.0.0.1:5000/api/generate-text \
  -H "Content-Type: application/json" \
  -d @request.json

예상 응답 예시

{
  "topic": "자연이 주는 위로",
  "category": "블로그 게시물",
  "generated_text": "푸른 하늘과 꽃이 피어난 들판은..."
}

다음 단계

Part 6에서는 지금까지 만든 API들을 Flutter 앱과 연결해,
사진 업로드 → 주제 선택 → 글 생성 → 복사하기 흐름을 구현합니다.


TechTinkerer's에서 더 알아보기

구독을 신청하면 최신 게시물을 이메일로 받아볼 수 있습니다.

댓글 남기기

  • Mastering CSS Grid and Flexbox for Responsive Web Design

    [Tutorial] · 2026-05-06 02:31 UTC Mastering CSS Grid and Flexbox for Responsive Web Design 💡 TL;DR Understand the fundamentals of CSS Grid and Flexbox, including layout models and responsive design, to build robust and adaptable web applications. 📚 Learning Objectives This tutorial introduces the basics of CSS Grid and Flexbox, covering layout models, box sizing,…

  • Complete Guide to HTML5 Forms and Validation

    [Tutorial] · 2026-05-06 01:29 UTC Complete Guide to HTML5 Forms and Validation 💡 TL;DR Master HTML5 forms and validation to build accessible and functional web applications. 📚 Learning Objectives This tutorial covers the basics of HTML5 forms, including validation, semantic attributes, and accessibility features. Learn how to create robust and user-friendly forms that meet modern…

  • Building a Simple Web Application with React

    [Tutorial] · 2026-05-06 00:27 UTC Building a Simple Web Application with React 💡 TL;DR Learn how to build a basic web application with React using components, state management, and routing. 📚 Learning Objectives This tutorial covers the basics of creating a simple web application with React, including components, state management, and routing. Learners will gain…

  • C++ Template Metaprogramming for Beginners

    [Tutorial] · 2026-05-05 23:24 UTC C++ Template Metaprogramming for Beginners 💡 TL;DR Master C++ template metaprogramming to perform compile-time calculations and optimize your code. 📚 Learning Objectives Learn how to master C++ template metaprogramming, a powerful technique for performing compile-time calculations. This guide covers its benefits, key concepts, and practical examples to help you get…

  • Understanding Pointers and Memory Management in C++

    [Tutorial] · 2026-04-30 05:10 UTC Understanding Pointers and Memory Management in C++ 💡 TL;DR Mastering pointers in C++ is crucial for efficient memory management and writing effective code. 📚 Learning Objectives This tutorial covers the fundamentals of pointers in C++, including declaration, initialization, and memory management. Students will learn how to effectively use pointers to…

← 뒤로

응답해 주셔서 감사합니다. ✨

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기