App.py запускается и создает функцию счетчика. Однако он выводит вторую половину примера текстового файла вики вместо простой сводки, созданной сценарием model.py. App.py и model.py — это два отдельных файла. Намерение состояло в том, чтобы создать языковую модель, которая использует статистику для получения сводных результатов. Где ошибка?
# -------------------- App.py --------------------
import argparse # Input analysis (parsing) processed with grammar.
import sys # System exit.
import os # File path.
import time # Timestamping.
# Import (AI text summarization and load text file) functions from called upon modules.
from .model import summarize_text
from .utils import load_text
# Spinner animation for longer operations. Heighten user experience, (UX).
def spinner():
# Function to cycle through characters.
while True:
for frame in "|/-\\":
yield frame
# Define main CLI function as script runs.
def main():
# Initialize parser (analysis) with description.
parser = argparse.ArgumentParser(
description="AI-powered text summarizer CLI tool"
)
# Input the text file we want to consolidate.
parser.add_argument(
"input_file",
type=str,
help="Path to the text file you want to summarize"
)
# Output text file naming.
parser.add_argument(
"-o", "--output",
type=str,
help="Optional output file to save the summary"
)
# Allow for plenty of, (verbose), documentation of each step of process (ideal for teaching and auditing).
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="Enable verbose mode for detailed logs"
)
# Analyse the user argument.
args = parser.parse_args()
# Qualify input file.
if not os.path.exists(args.input_file):
print(f"Error: File not found: {args.input_file}")
sys.exit(1)
# Load and read text file.
if args.verbose:
print(f"[INFO] Loading file: {args.input_file}")
text = load_text(args.input_file)
# Prevent empty file summarization.
if not text.strip():
print("Error: File is empty. Cannot summarize an empty text file.")
sys.exit(1)
# Show summarization is rendering
if args.verbose:
print("Generating summary...")
# Display spinner.
spin = spinner()
for _ in range(10):
sys.stdout.write(next(spin))
sys.stdout.flush()
time.sleep(0.05)
sys.stdout.write("\b")
# Executive AI summarization.
summary = summarize_text(text)
# Print summary to console.
print("\n=== SUMMARY RESULT ===\n")
print(summary)
# Save output to file if requested.
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(summary)
print(f"\n Summary saved to: {args.output}")
# Direct execution only.
if __name__ == "__main__":
main()
# ------------------- Model.py -------------------
import re
from collections import Counter
def summarize_text(text):
"""
Lightweight extractive summarizer:
- Extracts sentences
- Computes keyword frequency
- Selects best 1–2 sentences
- Produces a clean, grammatical summary
"""
# --- 1. Split text into sentences ---
sentences = [s.strip() for s in re.split(r'(?
Подробнее здесь: [url]https://stackoverflow.com/questions/79833002/text-summarizer-produces-second-half-of-exampe-text-rather-than-complete-text-su[/url]
App.py запускается и создает функцию счетчика. Однако он выводит вторую половину примера текстового файла вики вместо простой сводки, созданной сценарием model.py. App.py и model.py — это два отдельных файла. Намерение состояло в том, чтобы создать языковую модель, которая использует статистику для получения сводных результатов. Где ошибка? [code]# -------------------- App.py --------------------
import argparse # Input analysis (parsing) processed with grammar. import sys # System exit. import os # File path. import time # Timestamping.
# Import (AI text summarization and load text file) functions from called upon modules. from .model import summarize_text from .utils import load_text
# Spinner animation for longer operations. Heighten user experience, (UX). def spinner(): # Function to cycle through characters. while True: for frame in "|/-\\": yield frame
# Define main CLI function as script runs. def main(): # Initialize parser (analysis) with description. parser = argparse.ArgumentParser( description="AI-powered text summarizer CLI tool" ) # Input the text file we want to consolidate. parser.add_argument( "input_file", type=str, help="Path to the text file you want to summarize" ) # Output text file naming. parser.add_argument( "-o", "--output", type=str, help="Optional output file to save the summary" ) # Allow for plenty of, (verbose), documentation of each step of process (ideal for teaching and auditing). parser.add_argument( "-v", "--verbose", action="store_true", help="Enable verbose mode for detailed logs" )
# Analyse the user argument. args = parser.parse_args()
# Qualify input file. if not os.path.exists(args.input_file): print(f"Error: File not found: {args.input_file}") sys.exit(1)
# Load and read text file. if args.verbose: print(f"[INFO] Loading file: {args.input_file}") text = load_text(args.input_file)
# Prevent empty file summarization. if not text.strip(): print("Error: File is empty. Cannot summarize an empty text file.") sys.exit(1)
# Show summarization is rendering if args.verbose: print("Generating summary...")
# Display spinner. spin = spinner() for _ in range(10): sys.stdout.write(next(spin)) sys.stdout.flush() time.sleep(0.05) sys.stdout.write("\b")
# Executive AI summarization. summary = summarize_text(text)
# Print summary to console. print("\n=== SUMMARY RESULT ===\n") print(summary)
# Save output to file if requested. if args.output: with open(args.output, "w", encoding="utf-8") as f: f.write(summary)
print(f"\n Summary saved to: {args.output}")
# Direct execution only. if __name__ == "__main__": main()