Spaces:
Runtime error
Runtime error
File size: 5,978 Bytes
f439c8b cf70d81 f439c8b a3354db b5b699f 1153626 b5b699f 128f810 b5b699f 1153626 128f810 cf70d81 b5b699f f439c8b cf70d81 f439c8b 4dcca54 f439c8b cf70d81 3fe637a f439c8b 3fe637a cf70d81 f439c8b e51357b f439c8b 4dcca54 f439c8b cf70d81 f439c8b b5b699f b3adc23 f439c8b b5b699f 2f0825e f439c8b b5b699f e51357b f439c8b b3adc23 f439c8b b5b699f |
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 |
import gradio as gr
import os
import openai
from newspaper import Article
import json
import re
from transformers import GPT2Tokenizer
import requests
import time
def text_prompt(page_url, azure_endpoint, contrase帽a, temp):
# Reemplazar estas l铆neas con cadenas de texto fijas
request = """Analizar el siguiente texto de una noticia en prensa y generar un informe tipo KYC (Know Your Customer) para an谩lisis de riesgos, considerando los siguientes aspectos:
1. Identificaci贸n de las partes involucradas (personas, empresas, entidades)
2. Actividades sospechosas o inusuales descritas en el texto
Una vez generada la respuesta, aplicale formato HTML"""
system_role = """Actua como analista de riesgos especializado en cumplimiento normativo y KYC (Know Your Customer).
Tendr谩s una s贸lida formaci贸n en finanzas, derecho o gesti贸n, y estar谩s familiarizado con la normativa local e internacional relacionada con la prevenci贸n del blanqueo de capitales y la financiaci贸n del terrorismo.
Poseer谩s avanzadas capacidades anal铆ticas y de investigaci贸n, lo que te permitir谩 evaluar eficazmente la informaci贸n facilitada en las noticias y determinar el nivel de riesgo asociado a las partes implicadas.
Tambi茅n tendr谩s excelentes dotes de comunicaci贸n escrita y verbal para presentar de forma clara y concisa las conclusiones en un informe accesible a los ejecutivos y otras partes interesadas de la organizaci贸n.
Adem谩s, estar谩s al d铆a de las tendencias y novedades en el 谩mbito del cumplimiento de la normativa y la gesti贸n de riesgos.
El formato de la respuesta ser谩 siempre HMTL."""
start_time = time.time()
try:
headers = {'User-Agent': 'Chrome/83.0.4103.106'}
response = requests.get(page_url, headers=headers)
html = response.text
page = Article('')
page.set_html(html)
page.parse()
except Exception as e:
return "", f"--- An error occurred while processing the URL: {e} ---", ""
url_processing_time = time.time() - start_time
print(f"URL processing time: {url_processing_time:.4f} seconds")
start_time = time.time()
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
sentences = page.text.split('.')
tokens = []
page_text = ""
for sentence in sentences:
tokens.extend(tokenizer.tokenize(sentence))
# Trim text to a maximum of 3000 tokens
if len(tokens) > 3000:
break
page_text += sentence + ". "
# Delete the last space
page_text = page_text.strip()
num_tokens = len(tokens)
tokenization_time = time.time() - start_time
print(f"Tokenization time: {tokenization_time:.4f} seconds")
if num_tokens > 10:
# define azure openai context
openai.api_type = "azure"
openai.api_base = azure_endpoint
openai.api_version = "2023-03-15-preview"
openai.api_key = contrase帽a
# get the response from Azure OpenAI API
start_time = time.time()
try:
response = openai.ChatCompletion.create(
engine="gpt-35-turbo-version-0301",
messages=[
{"role": "system", "content": system_role},
{"role": "user", "content": request + "\n\n" + 'Text:\n\n"' + page_text + '\n"'}
],
max_tokens=1024,
temperature=temp,
top_p=1.0,
)
# get the response text
response_text = response['choices'][0]['message']['content']
total_tokens = response["usage"]["total_tokens"]
# clean the response text
response_text = re.sub(r'\s+', ' ', response_text)
response_text = f"#### [{page.title}]({page_url})\n\n{response_text.strip()}"
total_tokens_str = str(total_tokens) + " (${:.2f} USD)".format(total_tokens/1000*0.002)
api_processing_time = time.time() - start_time
print(f"API processing time: {api_processing_time:.4f} seconds")
return page.text, response_text, total_tokens_str
except Exception as e:
return page.text, f"--- An error occurred while processing the request: {e} ---", num_tokens
return page.text, "--- Check API-Key or Min number of tokens:", str(num_tokens)
# define the gradio interface
iface = gr.Interface(
fn=text_prompt,
inputs=[
gr.Textbox(lines=1, placeholder="Enter the Article's URL here...", label="Article's URL to analyse:", type="text"),
gr.Textbox(lines=1, placeholder="Enter the MSFT Azure OpenAI endpoint here...", label="Azure endpoint:", type="text"),
gr.Textbox(lines=1, placeholder="Enter your API-key here...", label="API-Key:", type="password"),
gr.Slider(0.0,1.0, value=0.3, label="Temperature:")
],
outputs=[gr.Textbox(label="Text from URL:"), gr.Markdown(label="Output from GPT:"), gr.Markdown(label="Total Tokens:")],
examples=[["https://www.eleconomista.es/andalucia/noticias/11534190/12/21/Nueva-condena-a-ex-presidente-de-Invercaria-por-dar-300000-euros-a-una-empresa-inviable.html","","","0.2"],
["https://www.eleconomista.es/andalucia/noticias/11533733/12/21/El-juez-procesa-a-35-investigados-en-la-pieza-de-las-sobrecomisiones-de-los-ERE-.html","","","0.2"]
],
title="ChatGPT - KYC from URL",
description="""This tool allows to generate points of a KYC report based on the text retrieved from the URL using the [gpt-3.5-turbo] engine of MSFT Azure OpenAI.
Provide the url for text retrieval, your endopoint, api-key and the temperature to process the text."""
)
# error capturing in integration as a component
error_message = ""
try:
iface.queue(concurrency_count=5)
iface.launch()
except Exception as e:
error_message = "An error occurred: " + str(e)
iface.outputs[1].value = error_message
|