Update Summarizing_with_controllable_detail.ipynb (#1140)

pull/1141/head
Shyamal H Anadkat 4 weeks ago committed by GitHub
parent 0c010b211a
commit 43bd32a3ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -4,32 +4,46 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Summarizing with Controllable Detail"
"# Summarization with Controllable Detail"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The objective of this notebook is to demonstrate how to summarize large documents with a controllable level of detail. If you give a GPT model the task of summarizing a long document (e.g. 10k or more tokens), you'll tend to get back a relatively short summary that isn't proportional to the length of the document. For instance, a summary of a 20k token document will not be twice as long as a summary of a 10k token document. One way we can fix this is to split our document up into pieces, and produce a summary piecewise. After many queries to a GPT model, the full summary can be reconstructed. By controlling the number of text chunks and their sizes, we can ultimately control the level of detail in the output."
"The objective of this notebook is to demonstrate how to summarize large documents with a controllable level of detail.\n",
" \n",
"If you give a GPT model the task of summarizing a long document (e.g. 10k or more tokens), you'll tend to get back a relatively short summary that isn't proportional to the length of the document. For instance, a summary of a 20k token document will not be twice as long as a summary of a 10k token document. One way we can fix this is to split our document up into pieces, and produce a summary piecewise. After many queries to a GPT model, the full summary can be reconstructed. By controlling the number of text chunks and their sizes, we can ultimately control the level of detail in the output."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"execution_count": 41,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:35.305706Z",
"start_time": "2024-04-10T05:19:35.303535Z"
}
},
"outputs": [],
"source": [
"import openai\n",
"import tiktoken\n",
"import os\n",
"from typing import List, Tuple, Optional\n",
"\n",
"from openai import OpenAI\n",
"import tiktoken\n",
"from tqdm import tqdm"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"execution_count": 42,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:35.325026Z",
"start_time": "2024-04-10T05:19:35.322414Z"
}
},
"outputs": [],
"source": [
"# open dataset containing part of the text of the Wikipedia page for the United States\n",
@ -39,14 +53,19 @@
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"execution_count": 43,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:35.364483Z",
"start_time": "2024-04-10T05:19:35.348213Z"
}
},
"outputs": [
{
"data": {
"text/plain": "15781"
},
"execution_count": 3,
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
@ -66,17 +85,24 @@
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"execution_count": 44,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:35.375619Z",
"start_time": "2024-04-10T05:19:35.365818Z"
}
},
"outputs": [],
"source": [
"client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n",
"\n",
"def get_chat_completion(messages, model='gpt-3.5-turbo'):\n",
" response = openai.ChatCompletion.create(\n",
" response = client.chat.completions.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0,\n",
" )\n",
" return response.choices[0].message['content']"
" return response.choices[0].message.content"
]
},
{
@ -88,8 +114,13 @@
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"execution_count": 45,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:35.382790Z",
"start_time": "2024-04-10T05:19:35.376721Z"
}
},
"outputs": [],
"source": [
"def tokenize(text: str) -> List[str]:\n",
@ -97,7 +128,9 @@
" return encoding.encode(text)\n",
"\n",
"\n",
"def chunk_on_delimiter(input_string, max_tokens, delimiter):\n",
"# This function chunks a text into smaller pieces based on a maximum token count and a delimiter.\n",
"def chunk_on_delimiter(input_string: str,\n",
" max_tokens: int, delimiter: str) -> List[str]:\n",
" chunks = input_string.split(delimiter)\n",
" combined_chunks, _, dropped_chunk_count = combine_chunks_with_no_minimum(\n",
" chunks, max_tokens, chunk_delimiter=delimiter, add_ellipsis_for_overflow=True\n",
@ -108,12 +141,13 @@
" return combined_chunks\n",
"\n",
"\n",
"# This function combines text chunks into larger blocks without exceeding a specified token count. It returns the combined text blocks, their original indices, and the count of chunks dropped due to overflow.\n",
"def combine_chunks_with_no_minimum(\n",
" chunks: List[str],\n",
" max_tokens: int,\n",
" chunk_delimiter=\"\\n\\n\",\n",
" header: Optional[str] = None,\n",
" add_ellipsis_for_overflow=False,\n",
" chunks: List[str],\n",
" max_tokens: int,\n",
" chunk_delimiter=\"\\n\\n\",\n",
" header: Optional[str] = None,\n",
" add_ellipsis_for_overflow=False,\n",
") -> Tuple[List[str], List[int]]:\n",
" dropped_chunk_count = 0\n",
" output = [] # list to hold the final combined chunks\n",
@ -127,8 +161,8 @@
" if len(tokenize(chunk_delimiter.join(chunk_with_header))) > max_tokens:\n",
" print(f\"warning: chunk overflow\")\n",
" if (\n",
" add_ellipsis_for_overflow\n",
" and len(tokenize(chunk_delimiter.join(candidate + [\"...\"]))) <= max_tokens\n",
" add_ellipsis_for_overflow\n",
" and len(tokenize(chunk_delimiter.join(candidate + [\"...\"]))) <= max_tokens\n",
" ):\n",
" candidate.append(\"...\")\n",
" dropped_chunk_count += 1\n",
@ -156,13 +190,20 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can define a utility to summarize text with a controllable level of detail (note the detail parameter)."
"Now we can define a utility to summarize text with a controllable level of detail (note the detail parameter).\n",
"\n",
"The function first determines the number of chunks by interpolating between a minimum and a maximum chunk count based on a controllable detail parameter. It then splits the text into chunks and summarizes each chunk."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"execution_count": 46,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:35.390876Z",
"start_time": "2024-04-10T05:19:35.385076Z"
}
},
"outputs": [],
"source": [
"def summarize(text: str,\n",
@ -171,7 +212,7 @@
" additional_instructions: Optional[str] = None,\n",
" minimum_chunk_size: Optional[int] = 500,\n",
" chunk_delimiter: str = \".\",\n",
" summarize_recursively = False,\n",
" summarize_recursively=False,\n",
" verbose=False):\n",
" \"\"\"\n",
" Summarizes a given text by splitting it into chunks, each of which is summarized individually. \n",
@ -195,7 +236,7 @@
" It then splits the text into chunks and summarizes each chunk. If `summarize_recursively` is True, each summary is based on the previous summaries, \n",
" adding more context to the summarization process. The function returns a compiled summary of all chunks.\n",
" \"\"\"\n",
" \n",
"\n",
" # check detail is set correctly\n",
" assert 0 <= detail <= 1\n",
"\n",
@ -254,8 +295,13 @@
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"execution_count": 47,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:47.541096Z",
"start_time": "2024-04-10T05:19:35.391911Z"
}
},
"outputs": [
{
"name": "stdout",
@ -269,7 +315,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 1/1 [00:05<00:00, 5.98s/it]\n"
"100%|██████████| 1/1 [00:07<00:00, 7.31s/it]\n"
]
}
],
@ -279,8 +325,13 @@
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"execution_count": 48,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:19:58.724212Z",
"start_time": "2024-04-10T05:19:47.542129Z"
}
},
"outputs": [
{
"name": "stdout",
@ -294,7 +345,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 5/5 [00:15<00:00, 3.18s/it]\n"
"100%|██████████| 5/5 [00:09<00:00, 1.97s/it]\n"
]
}
],
@ -304,8 +355,13 @@
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"execution_count": 49,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:20:16.216023Z",
"start_time": "2024-04-10T05:19:58.725014Z"
}
},
"outputs": [
{
"name": "stdout",
@ -319,7 +375,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 8/8 [00:19<00:00, 2.46s/it]\n"
"100%|██████████| 8/8 [00:16<00:00, 2.08s/it]\n"
]
}
],
@ -329,8 +385,13 @@
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"execution_count": 50,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:20:46.941240Z",
"start_time": "2024-04-10T05:20:16.225524Z"
}
},
"outputs": [
{
"name": "stdout",
@ -344,7 +405,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 14/14 [00:37<00:00, 2.69s/it]\n"
"100%|██████████| 14/14 [00:30<00:00, 2.15s/it]\n"
]
}
],
@ -354,8 +415,13 @@
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"execution_count": 51,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:21:44.913140Z",
"start_time": "2024-04-10T05:20:46.953285Z"
}
},
"outputs": [
{
"name": "stdout",
@ -369,7 +435,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 27/27 [01:20<00:00, 2.99s/it]\n"
"100%|██████████| 27/27 [00:57<00:00, 2.13s/it]\n"
]
}
],
@ -379,8 +445,13 @@
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"execution_count": 52,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:22:57.760218Z",
"start_time": "2024-04-10T05:21:44.921275Z"
}
},
"outputs": [
{
"name": "stdout",
@ -394,7 +465,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 33/33 [01:25<00:00, 2.58s/it]\n"
"100%|██████████| 33/33 [01:12<00:00, 2.20s/it]\n"
]
}
],
@ -411,46 +482,58 @@
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"execution_count": 53,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:22:57.782389Z",
"start_time": "2024-04-10T05:22:57.763041Z"
}
},
"outputs": [
{
"data": {
"text/plain": "[291, 681, 965, 1734, 3542, 4182]"
"text/plain": "[307, 494, 839, 1662, 3552, 4128]"
},
"execution_count": 13,
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# lengths of summaries\n",
"[len(tokenize(x)) for x in [summary_with_detail_0, summary_with_detail_pt1, summary_with_detail_pt2, summary_with_detail_pt4, summary_with_detail_pt8, summary_with_detail_1]]"
"[len(tokenize(x)) for x in\n",
" [summary_with_detail_0, summary_with_detail_pt1, summary_with_detail_pt2, summary_with_detail_pt4,\n",
" summary_with_detail_pt8, summary_with_detail_1]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's inspect the summaries to get a feel for what that means."
"Let's inspect the summaries to see how the level of detail changes with the `detail` parameter set to 0, 0.1, 0.2, 0.4, 0.8, and 1 respectively."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"execution_count": 54,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:22:57.785881Z",
"start_time": "2024-04-10T05:22:57.783455Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The United States of America is a diverse country located in North America, with a population exceeding 334 million. It is a federation of 50 states, a federal capital district, and various territories. The country has a rich history, from the migration of Paleo-Indians over 12,000 years ago to the American Revolution and the Civil War. The U.S. emerged as a superpower after World War II and played a significant role in the Cold War era.\n",
"The United States of America is a diverse country located in North America, with a population exceeding 334 million. It is a federation of 50 states, a federal capital district, and various territories. The country has a rich history, from the migration of Paleo-Indians over 12,000 years ago to the British colonization and the American Revolution. The U.S. has gone through significant events like the Civil War, World War II, and the Cold War, emerging as a superpower after the collapse of the Soviet Union.\n",
"\n",
"The U.S. government is a presidential constitutional republic with three separate branches: legislative, executive, and judicial. The country has a strong emphasis on liberty, equality under the law, individualism, and limited government. Economically, the U.S. has the largest nominal GDP in the world and is a leader in economic competitiveness, innovation, and human rights. The U.S. is also a founding member of various international organizations.\n",
"The U.S. government is a presidential constitutional republic with three separate branches: legislative, executive, and judicial. The country has a strong emphasis on liberty, equality under the law, individualism, and limited government. Economically, the U.S. has the largest nominal GDP in the world and is a leader in economic competitiveness, innovation, and human rights. The U.S. is also a founding member of various international organizations like the UN, World Bank, and NATO.\n",
"\n",
"The U.S. has a rich cultural landscape, with influences from various ethnic groups and traditions. American literature, music, cinema, theater, and visual arts have made significant contributions to global culture. The country is known for its diverse cuisine, with dishes influenced by various immigrant groups. The U.S. also has a strong tradition in education, with a focus on higher learning and research.\n",
"The U.S. has a rich cultural landscape, with influences from various ethnic groups and traditions. American literature, music, cinema, and theater have made significant contributions to global culture. The country is known for its diverse cuisine, with dishes influenced by various immigrant groups. The U.S. also has a strong presence in the fashion industry, with New York City being a global fashion capital.\n",
"\n",
"Overall, the United States is a country with a rich history, diverse culture, and significant global influence in various fields such as politics, economics, and the arts.\n"
"Overall, the United States is a country with a rich history, diverse population, strong economy, and significant cultural influence on the world stage.\n"
]
}
],
@ -460,28 +543,33 @@
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"execution_count": 55,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:22:57.788969Z",
"start_time": "2024-04-10T05:22:57.786691Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The United States of America is a country located in North America, consisting of 50 states, a federal capital district, and various territories. It has a rich history, from the arrival of Paleo-Indians over 12,000 years ago to British colonization, the American Revolution, and the Civil War. The U.S. is a presidential constitutional republic with a strong emphasis on liberty, equality, and limited government. It is a global economic powerhouse, with the largest nominal GDP since 1890 and significant influence in international organizations. The country's history includes European colonization, conflicts with Native Americans, the Revolutionary War, and westward expansion. The U.S. Constitution, drafted in 1787, established a federal government with three branches and a system of checks and balances. The U.S. has played a significant role in world events, including World War II and the Cold War, emerging as a superpower after the collapse of the Soviet Union.\n",
"The United States of America is a country located in North America, consisting of 50 states, a federal capital district, and various territories. It has a rich history, from the arrival of Paleo-Indians over 12,000 years ago to British colonization and the American Revolution. The U.S. expanded across North America, faced sectional divisions over slavery, and emerged as a global superpower after World War II. The country has a presidential constitutional republic with three branches of government and a strong emphasis on liberty, equality, and limited government. Economically, the U.S. is a major player with the largest nominal GDP in the world and significant influence in various international organizations. The country's name, history, and expansion are detailed, including key events like the Declaration of Independence, the Revolutionary War, and the Louisiana Purchase.\n",
"\n",
"The text discusses key events in American history from the Missouri Compromise to the rise of the United States as a superpower, the Cold War era, and contemporary history. It covers topics such as the Civil War, Reconstruction, post-Civil War era, immigration, industrialization, World Wars, Cold War, civil rights movement, and modern events like the September 11 attacks and the Great Recession. The text highlights significant developments in American society, politics, and economy over the years.\n",
"The text discusses key events in American history, including the Missouri Compromise, Indian removal policies, the Civil War, Reconstruction era, post-Civil War developments, rise as a superpower, Cold War era, and contemporary history. It highlights significant events such as the Trail of Tears, California Gold Rush, Reconstruction Amendments, immigration waves, World Wars, Cold War tensions, civil rights movement, economic developments, technological advancements, and major conflicts like the Gulf War and War on Terror. The text also mentions social changes, economic challenges like the Great Depression and Great Recession, and political developments leading to increased polarization in the 2010s.\n",
"\n",
"The text discusses the geography, climate, biodiversity, conservation efforts, government and politics, political parties, subdivisions, and foreign relations of the United States. It highlights the country's physical features, climate diversity, environmental issues, governmental structure, political parties, state subdivisions, and diplomatic relations. The text also mentions the Capitol attack in January 2021 and the country's environmental commitments and challenges.\n",
"The text discusses the geography, climate, biodiversity, conservation efforts, government, politics, political parties, subdivisions, and foreign relations of the United States. It highlights the country's physical features, climate diversity, environmental issues, governmental structure, political parties, state subdivisions, and diplomatic relations. The text also mentions the historical context of the country's political system, including the development of political parties and the structure of the federal government.\n",
"\n",
"The text discusses the United States' international relations, military capabilities, law enforcement, crime rates, economy, and scientific advancements. It highlights the country's membership in various international organizations, strong alliances with countries like the UK, Canada, and Japan, and its military spending and capabilities. The text also covers law enforcement agencies, incarceration rates, economic status as the world's largest economy, technological advancements, and scientific achievements, including the country's leadership in artificial intelligence and space exploration. Additionally, it addresses income inequality, poverty rates, and social welfare policies in the United States.\n",
"The text discusses the United States' international relations, military capabilities, law enforcement, crime rates, economy, and science and technology advancements. It highlights the country's membership in various international organizations, its military strength, economic dominance, income inequality, and technological innovations. The United States has strong diplomatic ties with several countries, a significant military presence globally, a large economy with high GDP, and is a leader in technological advancements and scientific research.\n",
"\n",
"The text provides information about various aspects of the United States, including its scientific and innovation rankings, energy consumption, transportation infrastructure, demographics, language diversity, immigration, religion, urbanization, and healthcare. The United States ranks high in scientific publications and patents, but also consumes a significant amount of fossil fuels and emits greenhouse gases. The country has a diverse population with various racial and ethnic groups, and English is the most commonly spoken language. Immigration plays a significant role in the U.S., with a large immigrant population. The country is religiously diverse, with a majority believing in a higher power. Urban areas are home to most Americans, with rapid population growth in many metropolitan areas. The U.S. has a complex healthcare system, with notable medical facilities like the Texas Medical Center in Houston.\n",
"The text discusses various aspects of the United States, including its scientific and innovation rankings, energy consumption, transportation infrastructure, demographics, language diversity, immigration, religion, urbanization, and healthcare. It highlights the country's achievements in scientific research, energy usage, transportation systems, population demographics, language diversity, immigration statistics, religious affiliations, urbanization trends, and healthcare facilities.\n",
"\n",
"The text discusses various aspects of life in the United States, including changes in life expectancy, healthcare, education, culture, literature, and mass media. It mentions that life expectancy in the U.S. has fluctuated due to factors like the COVID-19 pandemic, opioid overdoses, and suicides. The U.S. healthcare system is criticized for its high spending and poor outcomes compared to other countries. The education system is decentralized, with high spending per student. The U.S. has a diverse culture and society, with strong protections for free speech and progressive attitudes towards human sexuality. American literature has a rich history, influenced by various movements and authors. The mass media landscape includes major broadcasters, cable television, radio, and newspapers with global reach.\n",
"The text discusses various aspects of life in the United States, including changes in life expectancy, the healthcare system, education, culture, society, literature, and mass media. It highlights the impact of the COVID-19 pandemic on life expectancy, the disparities in healthcare outcomes, the structure of the education system, the cultural diversity and values in American society, the development of American literature, and the media landscape in the country. The text also touches on issues such as healthcare coverage, education spending, student loan debt, and the protection of free speech in the U.S.\n",
"\n",
"The text discusses various aspects of American culture, including alternative newspapers in major cities, popular websites, the video game market, theater, visual arts, music, fashion, cinema, and cuisine. It highlights the influence of American culture globally, such as in music, fashion, cinema, and cuisine. The text also mentions significant figures and events in American cultural history, such as the Tony Awards, Broadway theater, the Hudson River School, and the Golden Age of Hollywood. Additionally, it touches on the impact of American cuisine, the film industry, and the arts on both domestic and international audiences.\n",
"The text discusses various aspects of American culture, including alternative newspapers in major cities, popular websites, the video game market, theater, visual arts, music, fashion, cinema, and cuisine. It highlights the influence of American culture globally, such as in music, fashion, cinema, and cuisine. The text also mentions significant figures and events in American cultural history, such as the Tony Awards, Broadway theater, the Hudson River School in visual arts, and the Golden Age of Hollywood in cinema. Additionally, it touches on the development of American cuisine, including traditional dishes and the impact of immigrant groups on American food culture.\n",
"\n",
"The American fast-food industry, known for pioneering the drive-through format in the 1940s, is considered a symbol of U.S. marketing dominance. Major companies like McDonald's, Burger King, Pizza Hut, KFC, and Domino's Pizza have a global presence with numerous outlets worldwide.\n"
"The American fast-food industry, known for pioneering the drive-through format in the 1940s, is considered a symbol of U.S. marketing dominance. Major American companies like McDonald's, Burger King, Pizza Hut, Kentucky Fried Chicken, and Domino's Pizza have a significant global presence with numerous outlets worldwide.\n"
]
}
],
@ -498,14 +586,19 @@
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"execution_count": 56,
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-10T05:33:18.789246Z",
"start_time": "2024-04-10T05:22:57.789764Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 5/5 [00:17<00:00, 3.54s/it]"
"100%|██████████| 5/5 [10:19<00:00, 123.94s/it]"
]
},
{
@ -514,36 +607,39 @@
"text": [
"- The USA is a federation of 50 states, a federal capital district, and 326 Indian reservations.\n",
"- It has sovereignty over five major unincorporated island territories and various uninhabited islands.\n",
"- The population of the USA exceeds 334 million.\n",
"- The USA has the world's third-largest land area and largest maritime exclusive economic zone.\n",
"- The USA has had the largest nominal GDP in the world since 1890 and accounted for over 25% of the global economy in 2023.\n",
"- The country has a population exceeding 334 million.\n",
"- The USA has the world's third-largest land area and the largest maritime exclusive economic zone.\n",
"- The USA has had the largest nominal GDP in the world since 1890.\n",
"- In 2023, the USA accounted for over 25% of the global economy based on nominal GDP and 15% based on PPP.\n",
"- The USA has the highest median income per capita of any non-microstate.\n",
"- The USA ranks high in economic competitiveness, productivity, innovation, human rights, and higher education.\n",
"- The USA is a founding member of various international organizations such as the World Bank, IMF, NATO, and the UN Security Council.\n",
"\n",
"- In the early 1960s, President Lyndon Johnson's Great Society plan led to groundbreaking laws and policies to counteract institutional racism.\n",
"- By 1985, the majority of women aged 16 and older in the US were employed.\n",
"- In the 1990s, the US saw the longest economic expansion in its history, with advances in technology such as the World Wide Web and gene therapy.\n",
"- The US spent $877 billion on its military in 2022, the largest amount globally, accounting for 39% of global military spending and 3.5% of the country's GDP.\n",
"- The US has the third-largest combined armed forces in the world, behind China and India.\n",
"- As of January 2023, the US had the sixth highest per-capita incarceration rate globally, with almost 2 million people incarcerated.\n",
"- The US had a nominal GDP of $27 trillion in 2023, constituting over 25% of the global economy.\n",
"- The Great Society plan of President Lyndon Johnson's administration in the early 1960s resulted in groundbreaking laws and policies to counteract institutional racism.\n",
"- By 1985, the majority of women aged 16 and older in the U.S. were employed.\n",
"- In the 1990s, the U.S. saw the longest economic expansion in its history, with advances in technology such as the World Wide Web and the first gene therapy trial.\n",
"- The U.S. spent $877 billion on its military in 2022, the largest amount globally, making up 39% of global military spending and 3.5% of the country's GDP.\n",
"- The U.S. has the third-largest combined armed forces in the world, with about 800 bases and facilities abroad and deployments in 25 foreign countries.\n",
"- As of January 2023, the U.S. had the sixth highest per-capita incarceration rate globally, with almost 2 million people incarcerated.\n",
"- The U.S. had a nominal GDP of $27 trillion in 2023, the largest in the world, constituting over 25% of the global economy.\n",
"\n",
"- Real compounded annual GDP growth in the US was 3.3%, compared to 2.3% for the rest of the Group of Seven.\n",
"- The US ranks first in the world by disposable income per capita and nominal GDP, second by GDP (PPP) after China, and ninth by GDP (PPP) per capita.\n",
"- The US has 136 of the world's 500 largest companies headquartered in the country.\n",
"- The US dollar is the most used currency in international transactions and is the world's foremost reserve currency.\n",
"- The US ranked second in the Global Competitiveness Report in 2019.\n",
"- The US is the second-largest manufacturing country after China as of 2021.\n",
"- The US has the highest average household and employee income among OECD member states.\n",
"- The US has 735 billionaires and nearly 22 million millionaires as of 2023.\n",
"- In 2022, there were about 582,500 sheltered and unsheltered homeless persons in the US.\n",
"- The US receives approximately 81% of its energy from fossil fuels.\n",
"- The US has the highest vehicle ownership per capita in the world, with 910 vehicles per 1000 people.\n",
"- The US has 333 incorporated municipalities with populations over 100,000.\n",
"- Real compounded annual GDP growth in the U.S. was 3.3%, compared to 2.3% for the rest of the Group of Seven.\n",
"- The U.S. ranks first in the world by disposable income per capita and nominal GDP, second by GDP (PPP) after China, and ninth by GDP (PPP) per capita.\n",
"- The U.S. has 136 of the world's 500 largest companies headquartered there.\n",
"- The U.S. dollar is the most used currency in international transactions and is the world's foremost reserve currency.\n",
"- The U.S. ranked second in the Global Competitiveness Report in 2019, after Singapore.\n",
"- The U.S. is the second-largest manufacturing country after China as of 2021.\n",
"- Americans have the highest average household and employee income among OECD member states.\n",
"- The U.S. has 735 billionaires and nearly 22 million millionaires as of 2023.\n",
"- In 2022, there were about 582,500 sheltered and unsheltered homeless persons in the U.S.\n",
"- The U.S. receives approximately 81% of its energy from fossil fuels.\n",
"- The U.S. has the highest vehicle ownership per capita in the world, with 910 vehicles per 1000 people.\n",
"- The U.S. has the third-highest number of patent applications and ranked 3rd in the Global Innovation Index in 2023.\n",
"- The U.S. has the third-highest number of published scientific papers in 2022.\n",
"- The U.S. has a diverse population with 37 ancestry groups having more than one million members.\n",
"- The U.S. has the largest Christian population in the world.\n",
"- The average American life expectancy at birth was 77.5 years in 2022.\n",
"- Approximately one-third of the US adult population is obese, and another third is overweight.\n",
"- The US spends more on education per student than any other country in the world, averaging $12,794 per year per public elementary and secondary school student in 2016-2017.\n",
"- The U.S. spends more on education per student than any other country in the world.\n",
"\n",
"- The United States has the most Nobel Prize winners in history, with 411 awards won.\n",
"- American higher education is dominated by state university systems, with private universities enrolling about 20% of students.\n",
@ -551,11 +647,12 @@
"- Student loan debt in the U.S. has increased by 102% in the last decade, exceeding 1.7 trillion dollars as of 2022.\n",
"- Americans donated 1.44% of total GDP to charity, the highest rate in the world.\n",
"- The U.S. has the world's largest music market with a total retail value of $15.9 billion in 2022.\n",
"- The U.S. restaurant industry was projected at $899 billion in sales for 2020, employing over 15 million people.\n",
"- The United States is home to over 220 Michelin Star rated restaurants, with 70 in New York City alone.\n",
"- California produces 84% of all US wine, making the U.S. the fourth-largest wine producing country in the world.\n",
"- The United States restaurant industry was projected at $899 billion in sales for 2020, employing over 15 million people.\n",
"- The U.S. is home to over 220 Michelin Star rated restaurants, with 70 in New York City alone.\n",
"- California alone has 444 publishers, developers, and hardware companies in the video game market.\n",
"- The U.S. fast-food industry pioneered the drive-through format in the 1940s.\n",
"\n",
"- American companies with global presence include McDonald's, Burger King, Pizza Hut, Kentucky Fried Chicken, and Domino's Pizza\n",
"- American companies mentioned: McDonald's, Burger King, Pizza Hut, Kentucky Fried Chicken, Domino's Pizza\n",
"- These companies have numerous outlets around the world\n"
]
},
@ -568,7 +665,8 @@
}
],
"source": [
"summary_with_additional_instructions = summarize(united_states_wikipedia_text, detail=0.1, additional_instructions=\"Write in point form and focus on numerical data.\")\n",
"summary_with_additional_instructions = summarize(united_states_wikipedia_text, detail=0.1,\n",
" additional_instructions=\"Write in point form and focus on numerical data.\")\n",
"print(summary_with_additional_instructions)"
]
},
@ -583,26 +681,26 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 57,
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 5/5 [00:12<00:00, 2.40s/it]"
"100%|██████████| 5/5 [00:09<00:00, 1.99s/it]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"The United States of America is a country located in North America with 50 states, a federal capital district, and various territories. It has a rich history, from early indigenous migrations to European colonization, the American Revolution, Civil War, and emergence as a global superpower. The U.S. government is a presidential constitutional republic with a strong emphasis on liberty, equality, and limited government. Economically, the U.S. is a powerhouse with a significant global influence. The country has been involved in major historical events such as World War II, the Cold War, and the civil rights movement.\n",
"The text provides an overview of the United States, including its geography, history, government structure, economic status, and global influence. It covers the country's origins, colonization, independence, expansion, Civil War, post-war era, rise as a superpower, and involvement in the Cold War. The U.S. is described as a presidential constitutional republic with a strong emphasis on individual rights, liberty, and limited government. The text also highlights the country's economic prowess, cultural influence, and membership in various international organizations.\n",
"\n",
"In the 1960s, the U.S. saw significant social changes with President Lyndon Johnson's Great Society plan addressing institutional racism, the counterculture movement influencing attitudes towards drug use and sexuality, and opposition to the Vietnam War. The 1980s and 1990s marked the end of the Cold War, solidifying the U.S. as a superpower. The 1990s saw economic growth, technological advancements, and the Gulf War. The 21st century brought challenges like the September 11 attacks, the Great Recession, and increased political polarization. The U.S. has diverse geography and climate, rich biodiversity, and faces environmental issues. The government is a federal republic with a strong system of checks and balances, and a two-party political system. The U.S. has a significant global presence in foreign relations, a powerful military, and law enforcement agencies. Economically, it is a leading global player with a diverse economy and the world's largest GDP.\n",
"The text discusses the United States from the early 1960s to the present day, highlighting significant events such as President Lyndon Johnson's Great Society plan, the counterculture movement, societal changes, the end of the Cold War, the economic expansion of the 1990s, the September 11 attacks, the Great Recession, and political polarization. It also covers the country's geography, climate, biodiversity, conservation efforts, government structure, political parties, foreign relations, military strength, law enforcement, crime rates, and the economy, including its status as the world's largest economy.\n",
"\n",
"The text discusses the economic strength of the United States, highlighting its high GDP, disposable income per capita, and global economic influence. It mentions the dominance of the U.S. dollar in international transactions and its leading position in various economic sectors such as technology, finance, and manufacturing. The text also touches on income inequality, poverty rates, and social issues like homelessness and food insecurity in the country. Additionally, it covers the U.S.'s role in scientific innovation, energy consumption, transportation infrastructure, demographics, immigration, religion, urbanization, healthcare, and education.\n",
"The text discusses the economic status of the United States, highlighting its GDP growth, ranking in various economic indicators, dominance in global trade, and technological advancements. It also covers income distribution, poverty rates, and social issues like homelessness and food insecurity. The text further delves into the country's energy consumption, transportation infrastructure, demographics, immigration trends, religious diversity, urbanization, healthcare system, life expectancy, and education system.\n",
"\n",
"The text discusses various aspects of American culture and society, including education, literature, mass media, theater, visual arts, music, fashion, cinema, and cuisine. It highlights the country's achievements in education, with a global reputation for tertiary education and numerous top-ranking universities. The text also covers American values, ethnic diversity, free speech protections, and progressive attitudes towards human sexuality and LGBT rights. Additionally, it mentions the country's contributions to literature, mass media, theater, visual arts, music, and cuisine, showcasing its significant influence and global presence in these areas.\n",
"The text discusses various aspects of American culture and society, including education, literature, mass media, theater, visual arts, music, fashion, cinema, and cuisine. It highlights the country's achievements in education, with a focus on higher education and federal financial aid for students. The text also delves into American cultural values, ethnic diversity, and the country's strong protections of free speech. Additionally, it covers the development of American literature, mass media landscape, theater scene, visual arts movements, music genres, fashion industry, cinema history, and culinary traditions. The influence of American culture globally, as well as the economic impact of industries like music and restaurants, is also discussed.\n",
"\n",
"American fast-food chains like McDonald's, Burger King, Pizza Hut, Kentucky Fried Chicken, and Domino's Pizza have a widespread global presence with numerous outlets worldwide.\n"
]
@ -616,20 +714,16 @@
}
],
"source": [
"recursive_summary = summarize(united_states_wikipedia_text, detail=0.1, summarize_recursively=True, additional_instructions=\"Don't overuse repetitive phrases to introduce each section\")\n",
"recursive_summary = summarize(united_states_wikipedia_text, detail=0.1, summarize_recursively=True,\n",
" additional_instructions=\"Don't overuse repetitive phrases to introduce each section\")\n",
"print(recursive_summary)"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 17,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-04-10T05:33:30.123036Z",
"start_time": "2024-04-10T05:33:18.791253Z"
}
}
}
],

Loading…
Cancel
Save