File size: 6,985 Bytes
e62cec6
 
 
685549a
e62cec6
 
c9a39eb
 
 
 
 
 
e62cec6
 
 
 
 
 
 
 
6273f21
e62cec6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091b090
e62cec6
a981a76
e62cec6
 
 
 
 
 
 
 
 
 
 
685549a
c9a39eb
685549a
e62cec6
685549a
e62cec6
 
 
 
 
 
 
 
 
091b090
e62cec6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685549a
c9a39eb
685549a
e62cec6
 
 
 
 
 
 
 
 
 
 
 
c9a39eb
 
685549a
c9a39eb
e62cec6
 
 
 
 
 
 
1c4a43e
c9a39eb
e62cec6
 
2ab7f43
e62cec6
 
091b090
e62cec6
 
c9a39eb
e62cec6
 
8d570cc
e62cec6
 
 
 
 
 
 
 
 
 
 
 
9963898
c9a39eb
 
1c4a43e
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
import os
import fitz  
from docx import Document
from google import genai
from dotenv import load_dotenv

def set_up_api():
    load_dotenv()
    GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
    print(GOOGLE_API_KEY)
    client = genai.Client(api_key=GOOGLE_API_KEY)
    return client

####################### - TEXT EXTRACTION - #######################
def extract_text_from_pdf(pdf_path):
    # Mở file PDF
    doc = fitz.open(pdf_path)
    text = ""
    for page_num in range(doc.page_count):
        page = doc.load_page(page_num)
        text += page.get_text() 
    return text

def extract_text_from_docx(docx_path):
    # Mở file DOCX
    doc = Document(docx_path)
    text = ""
    for para in doc.paragraphs:
        text += para.text + "\n"
    return text

def extract_text_from_file(file_path):
    # Kiểm tra loại file và gọi hàm tương ứng
    file_extension = os.path.splitext(file_path)[1].lower()

    if file_extension == '.pdf':
        return extract_text_from_pdf(file_path)
    elif file_extension == '.docx':
        return extract_text_from_docx(file_path)
    else:
        raise ValueError("Unsupported file format. Only PDF and DOCX are supported.")
####################### - SEMANTIC CHUNKING - #######################
def split_text_by_semantics(text, chunks, client):
    prompt = f"""
    Bạn là một chuyên gia xử lý văn bản. Hãy chia văn bản sau thành chính xác {chunks} đoạn có ý nghĩa sao cho mỗi đoạn vừa đủ để giải thích trong khoảng 3 đến 5 câu.

    Văn bản:
    {text}

    Định dạng đầu ra:
    - Phần 1: [Nội dung]
    - Phần 2: [Nội dung]
    - Phần 3: [Nội dung]
    """

    try:
        response = client.models.generate_content(
            model="gemini-2.0-flash", contents=[prompt]
        )
        result_text = response.text.strip()
        print(result_text)

        chunks = result_text.split("- Phần ")
        chunks = [chunk.strip() for chunk in chunks if chunk]
        return chunks
    except Exception as e:
        print(f"Lỗi khi gọi API Gemini: {e}")
        return []

####################### - CONTENT GENERATION - #######################
def generate_explaination_for_chunks(chunks, client, analysis_level='basic', writting_style='academic', word_lower_limit=50, word_upper_limit=100):
    """
    Phân tích nội dung của văn bản theo mức độ và phong cách mong muốn.
    
    :param chunks: Danh sách các đoạn văn bản cần phân tích.
    :param text: Toàn bộ văn bản gốc.
    :param analysis_level: Mức độ phân tích ('basic' hoặc 'detailed').
    :param writting_style: Phong cách phân tích ('academic', 'popular', 'creative', 'humorous').
    :param word_limit: Số từ ước lượng cho mỗi phần tóm tắt.
    :return: Danh sách các phân tích tương ứng với từng đoạn.
    """
    
    level_prompts = {
        'basic': "Hãy đưa ra một bản tóm tắt ngắn gọn, tập trung vào nội dung chính.",
        'detailed': "Hãy phân tích chuyên sâu từng phần, làm rõ ý nghĩa, ngữ cảnh và các yếu tố quan trọng."
    }
    
    writting_style_prompts = {
        'academic': "Phân tích theo phong cách học thuật, sử dụng ngôn ngữ chuyên sâu và lập luận chặt chẽ.",
        'popular': "Trình bày theo phong cách phổ thông, dễ hiểu và phù hợp với nhiều đối tượng.",
        'creative': "Giải thích một cách sáng tạo, sử dụng hình ảnh ẩn dụ và cách diễn đạt thú vị.",
        'humorous': "Phân tích theo phong cách hài hước, thêm vào yếu tố vui nhộn và bất ngờ."
    }
    
    overview_prompt = f"""
    Đây là một văn bản có nội dung quan trọng. Bạn sẽ phân tích từng phần theo mức độ '{analysis_level}' và phong cách '{writting_style}'.
    Văn bản gồm các phần sau: {', '.join([f'Phần {i+1}' for i in range(len(chunks))])}.
    {level_prompts[analysis_level]}
    {writting_style_prompts[writting_style]}
    Mỗi phần không vượt quá {word_upper_limit} từ và không ít hơn {word_lower_limit} từ.
    """
    
    try:
        response = client.models.generate_content(
            model="gemini-2.0-flash", contents=[overview_prompt]
        )
        
        explanations = []
        for idx, chunk in enumerate(chunks, start=1):
            part_prompt = f"""
            Phân tích phần {idx} của văn bản.
            {level_prompts[analysis_level]}
            {writting_style_prompts[writting_style]}
            Nội dung phần này:
            {chunk}
            Hãy đảm bảo phần tóm tắt không vượt quá {word_upper_limit} từ và không ít hơn {word_lower_limit}.
            """
            
            part_response = client.models.generate_content(
                    model="gemini-2.0-flash", contents=[part_prompt]
                )
            print(part_response.text.strip())
            explanations.append(part_response.text.strip())
        
        return explanations
    
    except Exception as e:
        print(f"Lỗi khi gọi API Gemini: {e}")
        return [] 
def text_processing(file_path, chunks, analysis_level='basic', writting_style='academic', word_lower_limit = 100, word_upper_limit = 150):
    client = set_up_api()
    # Trích xuất văn bản từ file PDF
    text = extract_text_from_file(file_path=file_path)
    with open("./text.txt", "w", encoding="utf-8") as f:
        f.write(text)  
    # Tách văn bản theo ngữ nghĩa
    semantic_chunks = split_text_by_semantics(text, chunks, client)

    # Tạo thuyết minh cho từng phần semantic chunk
    explanations = generate_explaination_for_chunks(semantic_chunks, client, analysis_level=analysis_level, writting_style = writting_style, word_lower_limit = word_lower_limit, word_upper_limit=word_upper_limit)

    # Tạo thư mục nếu chưa tồn tại
    output_dir = "./"
    os.makedirs(output_dir, exist_ok=True)

    # Lưu từng câu vào file riêng biệt
    for chunk_idx, explanation in enumerate(explanations, start=1):
        # Tách đoạn phân tích thành các câu
        sentences = explanation.split('.')

        for sentence_idx, sentence in enumerate(sentences, start=1):
            sentence = sentence.strip()  # Loại bỏ khoảng trắng thừa
            if sentence:  # Kiểm tra nếu câu không rỗng
                output_file = os.path.join(output_dir, f"{chunk_idx}_{sentence_idx}.txt")  # Tên file dạng "chunkID_sentenceID.txt"
                with open(output_file, "w", encoding="utf-8") as f:
                    f.write(sentence.replace("*","").replace("#","") + ".")  # Giữ dấu chấm cuối câu
                print(f"Đã lưu: {output_file}")
if __name__ == "__main__":
    text_processing("phan-tich-hinh-tuong-nguoi-lai-do-song-da-2.pdf", chunks = 3)