File size: 3,442 Bytes
0c9b99b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# LEVEL 1, PROJECT 2: TEXT SUMMARIZATION
# As per the PORTFOLIO_ROADMAP.md, this script demonstrates using a pre-trained
# pipeline for another common NLP task: text summarization.

# Step 1: Ensure required libraries are installed.
# You can run this command in your terminal:
# pip install transformers torch

# Step 2: Import the pipeline function from the transformers library.
import torch
from transformers import pipeline

def get_pipeline():
    """
    Initializes and returns a summarization pipeline, using the GPU if available.
    """
    device = 0 if torch.cuda.is_available() else -1
    model = "sshleifer/distilbart-cnn-12-6"  # A well-known model for summarization
    print(f"Initializing summarization pipeline on device: {'GPU' if device == 0 else 'CPU'}")
    try:
        summarizer = pipeline("summarization", model=model, device=device)
        print("Pipeline initialized successfully.")
        return summarizer
    except Exception as e:
        print(f"Failed to initialize the pipeline. Please ensure you have an internet connection.")
        print(f"You may also need to run: pip install transformers torch")
        print(f"Error: {e}")
        return None

def summarize_text(summarizer, text, max_length=150, min_length=30):
    """
    Generates a summary for the given text using the provided pipeline.
    """
    if not summarizer or not text:
        return None
    
    print("\nPerforming text summarization...")
    try:
        summary = summarizer(text, max_length=max_length, min_length=min_length, do_sample=False)
        return summary[0]['summary_text']
    except Exception as e:
        print(f"An error occurred during summarization: {e}")
        return None

def main():
    """
    Main function to run the text summarization process.
    """
    summarizer = get_pipeline()
    
    if summarizer:
        long_text = """
        Hugging Face has emerged as a transformative force in the artificial intelligence
        and machine learning landscape, fundamentally altering how advanced AI technologies
        are developed, accessed, and deployed. The platform's foundational commitment to
        open-source principles has played a pivotal role in democratizing access to
        state-of-the-art models and tools, fostering widespread innovation and collaboration
        across the global AI community. The Hugging Face ecosystem is a meticulously designed
        framework comprising interconnected libraries, a centralized platform, and high-level
        tools, all unified by a steadfast commitment to open-source principles. This
        architecture streamlines the entire machine learning lifecycle, from data preparation
        and model training to deployment and community collaboration. At its core, the
        Transformers library provides access to an extensive collection of pre-trained models,
        while the Datasets library simplifies data handling. The Hub serves as a central
        repository for sharing models, datasets, and interactive applications called Spaces.
        """
        
        summary_text = summarize_text(summarizer, long_text, max_length=60, min_length=25)
        
        if summary_text:
            print("\n--- Text Summarization Results ---")
            print("\nOriginal Text:")
            print(long_text)
            print("\nSummarized Text:")
            print(summary_text)

if __name__ == "__main__":
    main()