{"id":13288986,"url":"https://github.com/Azure-Samples/function-csharp-ai-textsummarize","last_synced_at":"2025-03-10T06:33:53.630Z","repository":{"id":144908220,"uuid":"600280381","full_name":"Azure-Samples/function-csharp-ai-textsummarize","owner":"Azure-Samples","description":"This sample shows how to take text documents as a input via BlobTrigger, does Text Summarization \u0026 Sentiment Score processing using the AI Congnitive Language service, and then outputs to another text document using BlobOutput binding.","archived":false,"fork":false,"pushed_at":"2024-10-15T22:11:19.000Z","size":87,"stargazers_count":4,"open_issues_count":0,"forks_count":6,"subscribers_count":14,"default_branch":"main","last_synced_at":"2024-10-17T08:08:15.436Z","etag":null,"topics":["azd","azd-templates","azure","azure-function"],"latest_commit_sha":null,"homepage":"","language":"Bicep","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Azure-Samples.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-11T02:12:42.000Z","updated_at":"2024-10-15T22:11:24.000Z","dependencies_parsed_at":null,"dependency_job_id":"26f0ba0b-f542-43eb-b193-7fa137f335e7","html_url":"https://github.com/Azure-Samples/function-csharp-ai-textsummarize","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Ffunction-csharp-ai-textsummarize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Ffunction-csharp-ai-textsummarize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Ffunction-csharp-ai-textsummarize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Ffunction-csharp-ai-textsummarize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Azure-Samples","download_url":"https://codeload.github.com/Azure-Samples/function-csharp-ai-textsummarize/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242805566,"owners_count":20187996,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["azd","azd-templates","azure","azure-function"],"created_at":"2024-07-29T17:00:17.782Z","updated_at":"2025-03-10T06:33:50.692Z","avatar_url":"https://github.com/Azure-Samples.png","language":"Bicep","readme":"---\npage_type: sample\nlanguages:\n- azdeveloper\n- csharp\n- bicep\nproducts:\n- azure\n- azure-functions\n- ai-services\n- azure-cognitive-search\nurlFragment: function-csharp-ai-textsummarize\nname: Azure Functions - Text Summarization \u0026 Sentiment Analysis using AI Cognitive Language Service (C#-Isolated)\ndescription: This sample shows how to take text documents as a input via BlobTrigger, does Text Summarization \u0026 Sentiment Score processing using the AI Congnitive Language service, and then outputs to another text document using BlobOutput binding. Deploys to Flex Consumption hosting plan of Azure Functions.\n---\n\u003c!-- YAML front-matter schema: https://review.learn.microsoft.com/en-us/help/contribute/samples/process/onboarding?branch=main#supported-metadata-fields-for-readmemd --\u003e\n\n# Azure Functions\n## Text Summarization \u0026 Sentiment Analysis using AI Cognitive Language Service (C#-Isolated)\n\nThis sample shows how to take text documents as a input via BlobTrigger, does Text Summarization processing using the [AI Congnitive Language Service](https://learn.microsoft.com/en-us/azure/ai-services/language-service/) ExtractiveSummarize operations, then computes sentiment scores, and then outputs to another text document using BlobOutput binding.  Deploys to Flex Consumption hosting plan of Azure Functions.\n\n[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/function-csharp-ai-textsummarize)\n\n## Run on your local environment\n\n### Pre-reqs\n1) [.NET 8 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)\n2) [Azure Functions Core Tools](https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=v4%2Cmacos%2Ccsharp%2Cportal%2Cbash#install-the-azure-functions-core-tools)\n3) [Azurite](https://github.com/Azure/Azurite)\n\nThe easiest way to install Azurite is using a Docker container or the support built into Visual Studio:\n```bash\ndocker run -d -p 10000:10000 -p 10001:10001 -p 10002:10002 mcr.microsoft.com/azure-storage/azurite\n```\n4) [Azure Developer CLI](https://aka.ms/azd)\n5) Once you have your Azure subscription, run the following in a new terminal window to create all the AI Language and other resources needed:\n```bash\nazd provision\n```\n\nTake note of the value of `TEXT_ANALYTICS_ENDPOINT` which can be found in `./.azure/\u003cenv name from azd provision\u003e/.env`.  It will look something like:\n```bash\nTEXT_ANALYTICS_ENDPOINT=\"https://\u003cunique string\u003e.cognitiveservices.azure.com/\"\n```\n\nAlternatively you can [create a Language resource](https://portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics) in the Azure portal to get your key and endpoint. After it deploys, click Go to resource and view the Endpoint value.\n\n5) [Azure Storage Explorer](https://azure.microsoft.com/en-us/products/storage/storage-explorer/) or storage explorer features of [Azure Portal](https://portal.azure.com)\n6) Add this `local.settings.json` file to the `./text_summarization` folder to simplify local development.  Fill in the TEXT_ANALYTICS_ENDPOINT value per step 4.  This file will be gitignored to protectfrom committing to your repo.  \n```json\n{\n    \"IsEncrypted\": false,\n    \"Values\": {\n        \"AzureWebJobsStorage\": \"UseDevelopmentStorage=true\",\n        \"FUNCTIONS_WORKER_RUNTIME\": \"dotnet-isolated\",\n        \"TEXT_ANALYTICS_ENDPOINT\": \"\u003cinsert from step 4\u003e\"\n    }\n}\n```\n\n### Using VS Code\n1) Open the root folder in VS Code:\n```bash\ncode .\n```\n2) Ensure `local.settings.json` exists already using steps above\n3) Run and Debug by pressing `F5`\n4) Open Storage Explorer, Storage Accounts -\u003e Emulator -\u003e Blob Containers -\u003e and create a container `unprocessed-text` if it does not already exists\n5) Copy any .txt document file with text into the `unprocessed-text` container\n6) In the Azure extension of VS Code, open Azure:Workspace -\u003e Local Project -\u003e Functions -\u003e `summarize_function`.  Right-click and Execute Function now.  At the command palette prompt, enter the path to the storage blob you just uploaded: `unprocessed-text/\u003cyour_text_filename.txt\u003e`.  This will simulate an EventGrid trigger locally and your function will trigger and show output in the terminal.  \n\nYou will see AI analysis happen in the Terminal standard out.  The analysis will be saved in a .txt file in the `processed-text` blob container.\n\nNote, this newer mechanism for BlobTrigger with EventGrid source is documented in more detail here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-event-grid-blob-trigger?pivots=programming-language-python#run-the-function-locally. \n\n## Deploy to Azure\n\nThe easiest way to deploy this app is using the [Azure Developer CLI](https://aka.ms/azd).  If you open this repo in GitHub CodeSpaces the AZD tooling is already preinstalled.\n\nTo provision and deploy:\n1) Open a new terminal and do the following from root folder:\n```bash\nazd up\n```\n\n## Understand the Code\n\nThe main operation of the code starts with the `summarize_function` function in [summarize_function.cs](./text_summarization/summarize_function.cs).  The function is triggered by a Blob uploaded event using BlobTrigger, your code runs to do the processing with AI, and then the output is returned as another blob file simply by returning a value and using the BlobOutput binding.  \n\n```csharp\n[Function(\"summarize_function\")]\n[BlobOutput(\"processed-text/{name}-output.txt\")]\npublic async Task\u003cstring\u003e Run(\n    [BlobTrigger(\"unprocessed-text/{name}\", Source = BlobTriggerSource.EventGrid)] string myTriggerItem,\n    FunctionContext context)\n{\n    var logger = context.GetLogger(\"summarize_function\");\n    logger.LogInformation($\"Triggered Item = {myTriggerItem}\");\n\n    // Create client using Entra User or Managed Identity (no longer AzureKeyCredential)\n    // This requires a sub domain name to be set in endpoint URL for Managed Identity support\n    // See https://learn.microsoft.com/en-us/azure/ai-services/authentication#authenticate-with-microsoft-entra-id \n    var client = new TextAnalyticsClient(endpoint, new DefaultAzureCredential());\n\n    // analyze document text using Azure Cognitive Language Services\n    var summarizedText = await AISummarizeText(client, myTriggerItem, logger);\n    logger.LogInformation(Newline() + \"*****Summary*****\" + Newline() + summarizedText);\n\n    // Blob Output\n    return summarizedText;\n}\n```\n\nThe `AISummarizeText` helper function does the heavy lifting for summary extraction and sentiment analysis using the `TextAnalyticsClient` SDK from the [AI Language Services](https://learn.microsoft.com/en-us/azure/ai-services/language-service/):\n\n```csharp\nstatic async Task\u003cstring\u003e AISummarizeText(TextAnalyticsClient client, string document, ILogger logger)\n{\n    // ...\n    // Start analysis process.\n    ExtractiveSummarizeOperation operation = client.ExtractiveSummarize(WaitUntil.Completed, batchInput);\n\n    // View operation status.\n    summarizedText += $\"AnalyzeActions operation has completed\" + Newline();\n    summarizedText += $\"Created On   : {operation.CreatedOn}\" + Newline();\n    summarizedText += $\"Expires On   : {operation.ExpiresOn}\" + Newline();\n    summarizedText += $\"Id           : {operation.Id}\" + Newline();\n    summarizedText += $\"Status       : {operation.Status}\" + Newline();\n\n    // ...\n\n    // Perform sentiment analysis on document summary\n    var sentimentResult = await client.AnalyzeSentimentAsync(summarizedText);\n    Console.WriteLine($\"\\nSentiment: {sentimentResult.Value.Sentiment}\");\n    Console.WriteLine($\"Positive Score: {sentimentResult.Value.ConfidenceScores.Positive}\");\n    Console.WriteLine($\"Negative Score: {sentimentResult.Value.ConfidenceScores.Negative}\");\n    Console.WriteLine($\"Neutral Score: {sentimentResult.Value.ConfidenceScores.Neutral}\");\n\n    var summaryWithSentiment = summarizedText + $\"Sentiment: {sentimentResult.Value.Sentiment}\" + Newline();\n\n    return summaryWithSentiment;\n}\n\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAzure-Samples%2Ffunction-csharp-ai-textsummarize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAzure-Samples%2Ffunction-csharp-ai-textsummarize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAzure-Samples%2Ffunction-csharp-ai-textsummarize/lists"}