ll7098ll commited on
Commit
2d9e2da
·
verified ·
1 Parent(s): 87c2ac0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -31
app.py CHANGED
@@ -1,13 +1,19 @@
1
  import os
2
  import io
 
3
 
4
- import openai
5
  from PyPDF2 import PdfReader
6
- import gradio as gr
7
  from docx import Document
8
 
9
- # OpenAI API 키 설정
10
- openai.api_key = os.getenv("OPENAI_API_KEY")
 
 
 
 
 
11
 
12
  def extract_text_from_pdf(pdf_file):
13
  """PDF 파일에서 텍스트를 추출합니다."""
@@ -26,7 +32,7 @@ def generate_report(
26
  reference_pdfs,
27
  additional_instructions: str = "",
28
  ) -> io.BytesIO:
29
- """GPT-3.5-turbo를 사용하여 보고서를 생성하고 docx 파일로 변환합니다."""
30
  try:
31
  # 보고서 서식 PDF에서 텍스트 추출
32
  report_format = extract_text_from_pdf(report_format_pdf)
@@ -47,37 +53,44 @@ def generate_report(
47
  f"보고서를 최대한 자세하고 유익하게 작성하십시오."
48
  )
49
 
50
- # GPT-3.5-turbo API 호출
51
- response = openai.ChatCompletion.create(
52
- model="gpt-4-turbo",
53
- messages=[{"role": "user", "content": prompt}],
54
- )
55
 
56
- report_text = response.choices[0].message.content.strip()
 
 
57
 
58
- # docx 파일 생성 바이트 스트림에 저장
59
- doc = Document()
60
- doc.add_paragraph(report_text)
61
- doc_stream = io.BytesIO()
62
- doc.save(doc_stream)
63
- doc_stream.seek(0)
64
 
65
  return doc_stream
66
  except Exception as e:
67
  raise Exception(f"보고서 생성 중 오류가 발생했습니다: {e}")
68
 
69
- # Gradio 인터페이스 설정
70
- iface = gr.Interface(
71
- fn=generate_report,
72
- inputs=[
73
- gr.File(label="보고서 서식 PDF 업로드", file_types=[".pdf"]),
74
- gr.File(label="참고 PDF 파일 업로드", file_types=[".pdf"], file_count="multiple"),
75
- gr.Textbox(lines=3, label="추가 지침"),
76
- ],
77
- outputs=gr.File(label="생성된 보고서 (docx)", file_types=[".docx"]),
78
- title="보고서 생성 챗봇",
79
- description="서식 PDF, 참고 PDF 파일, 추가 지침을 입력하여 보고서를 생성하세요.",
80
- )
81
 
82
- # 인터페이스 실행
83
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import io
3
+ import time
4
 
5
+ import google.generativeai as genai
6
  from PyPDF2 import PdfReader
7
+ import streamlit as st
8
  from docx import Document
9
 
10
+ # Google Gemini API 키 설정 (Streamlit secrets 사용 권장)
11
+ genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
12
+
13
+ # Gemini 모델 설정
14
+ model = genai.GenerativeModel(
15
+ model_name="gemini-1.5-pro-exp-0827"
16
+ )
17
 
18
  def extract_text_from_pdf(pdf_file):
19
  """PDF 파일에서 텍스트를 추출합니다."""
 
32
  reference_pdfs,
33
  additional_instructions: str = "",
34
  ) -> io.BytesIO:
35
+ """Gemini를 사용하여 보고서를 생성하고 docx 파일로 변환합니다."""
36
  try:
37
  # 보고서 서식 PDF에서 텍스트 추출
38
  report_format = extract_text_from_pdf(report_format_pdf)
 
53
  f"보고서를 최대한 자세하고 유익하게 작성하십시오."
54
  )
55
 
56
+ # Gemini API 호출 (스트리밍)
57
+ full_text = ""
58
+ doc_stream = io.BytesIO()
 
 
59
 
60
+ response = model.generate_content(prompt, stream=True)
61
+ for chunk in response:
62
+ full_text += chunk.text
63
 
64
+ # docx 파일 업데이트 (매 chunk마다 docx 파일을 다시 생성하지 않고 업데이트)
65
+ doc = Document()
66
+ doc.add_paragraph(full_text)
67
+ doc.save(doc_stream)
68
+ doc_stream.seek(0)
69
+ time.sleep(0.05)
70
 
71
  return doc_stream
72
  except Exception as e:
73
  raise Exception(f"보고서 생성 중 오류가 발생했습니다: {e}")
74
 
75
+ # Streamlit 설정
76
+ st.title("보고서 생성 챗봇")
77
+ st.write("서식 PDF, 참고 PDF 파일, 추가 지침을 입력하여 보고서를 생성하세요.")
78
+
79
+ # 파일 업로드
80
+ report_format_pdf = st.file_uploader("보고서 서식 PDF 업로드", type="pdf")
81
+ reference_pdfs = st.file_uploader("참고 PDF 파일 업로드", type="pdf", accept_multiple_files=True)
82
+ additional_instructions = st.text_area("추가 지침", height=100)
 
 
 
 
83
 
84
+ # 보고서 생성 버튼
85
+ if st.button("보고서 생성") and report_format_pdf and reference_pdfs:
86
+ with st.spinner("보고서 생성 중..."):
87
+ try:
88
+ doc_stream = generate_report(report_format_pdf, reference_pdfs, additional_instructions)
89
+ st.download_button(
90
+ label="보고서 다운로드 (docx)",
91
+ data=doc_stream,
92
+ file_name="generated_report.docx",
93
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
94
+ )
95
+ except Exception as e:
96
+ st.error(e)