Spaces:
Runtime error
Runtime error
app and requirement.txt
Browse filesAdding the app.py and reuqiement.txt for easy access to the space.
- app.py +127 -0
- requirements.txt +1 -0
app.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from newsdataapi import NewsDataApiClient
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import pandas as pd
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
def creating_data_dir(directory_path):
|
10 |
+
# Use the os.makedirs() function to create the directory
|
11 |
+
# The 'exist_ok=True' argument allows it to run without errors if the directory already exists
|
12 |
+
os.makedirs(directory_path, exist_ok=True)
|
13 |
+
|
14 |
+
# Check if the directory was created successfully
|
15 |
+
if os.path.exists(directory_path):
|
16 |
+
print(f"Directory '{directory_path}' created successfully.")
|
17 |
+
else:
|
18 |
+
print(f"Failed to create directory '{directory_path}'.")
|
19 |
+
|
20 |
+
def retrieve_news_per_keyword(api,keywords):
|
21 |
+
# %time
|
22 |
+
for keyword in keywords:
|
23 |
+
# print(f"{api} \n {keyword}")
|
24 |
+
response = api.news_api( q= keyword , country = "us", language = 'en', full_content = True)
|
25 |
+
# writing to a file
|
26 |
+
file_path = os.path.join(directory_path, f"response_{keyword}.json")
|
27 |
+
with open(file_path, "w") as outfile:
|
28 |
+
json.dump(response, outfile)
|
29 |
+
|
30 |
+
print(f"News Response for keyword {keyword} is retrieved")
|
31 |
+
keywords.remove(keyword)
|
32 |
+
|
33 |
+
def combine_responses_into_one(directory_path):
|
34 |
+
|
35 |
+
# Use a list comprehension to get all file names in the directory
|
36 |
+
file_list = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]
|
37 |
+
|
38 |
+
#retrieve the file_keyword by extracting the string after "_"
|
39 |
+
# Extract the file_keyword from each filename
|
40 |
+
file_keywords = [filename.split('_')[1].split('.')[0] for filename in file_list]
|
41 |
+
|
42 |
+
|
43 |
+
# Initialize an empty list to store the combined JSON data
|
44 |
+
combined_json = []
|
45 |
+
|
46 |
+
# Loop through each file name
|
47 |
+
for filename in file_list:
|
48 |
+
# Read the current JSON file
|
49 |
+
with open(directory_path+'/'+filename, 'r') as file:
|
50 |
+
current_json = json.load(file)
|
51 |
+
|
52 |
+
# Extract the file_keyword from the filename
|
53 |
+
file_keyword = filename.split('_')[1].split('.')[0]
|
54 |
+
|
55 |
+
# Add the file_keyword to each result in the current JSON
|
56 |
+
for result in current_json['results']:
|
57 |
+
result['file_keyword'] = file_keyword
|
58 |
+
|
59 |
+
# Extend the combined JSON list with the results from the current JSON
|
60 |
+
combined_json.extend(current_json['results'])
|
61 |
+
print(f'{filename} is added to the combined json object')
|
62 |
+
# break # using the break to check the loop code always
|
63 |
+
|
64 |
+
# Save the combined_json object as a JSON file
|
65 |
+
with open('combined_news_response.json', 'w') as combined_file:
|
66 |
+
json.dump(combined_json, combined_file, indent=4)
|
67 |
+
|
68 |
+
def convert_json_to_csv(file_name):
|
69 |
+
json_data_df = pd.read_json(file_name)
|
70 |
+
# json_data_df.head()
|
71 |
+
|
72 |
+
columns = [ 'title', 'keywords', 'creator', 'description', 'content', 'pubDate', 'country', 'category', 'language', 'file_keyword' ]
|
73 |
+
csv_file_name = 'combined_news_response.csv'
|
74 |
+
json_data_df[columns].to_csv(csv_file_name)
|
75 |
+
print(f'{csv_file_name} is created')
|
76 |
+
|
77 |
+
|
78 |
+
# API key authorization, Initialize the client with your API key
|
79 |
+
NEWSDATA_API_KEY = "pub_2915202f68e543f70bb9aba9611735142c1fd"
|
80 |
+
keywords = [ "GDP", "CPI", "PPI", "Unemployment Rate", "Interest Rates", "Inflation", "Trade Balance", "Retail Sales", "Manufacturing Index", "Earnings Reports", "Revenue Growth", "Profit Margins", "Earnings Surprises", "Geopolitical Events", "Trade Tensions", "Elections", "Natural Disasters", "Global Health Crises", "Oil Prices", "Gold Prices", "Precious Metals", "Agricultural Commodities", "Federal Reserve", "ECB", "Forex Market", "Exchange Rates", "Currency Pairs", "Tech Company Earnings", "Tech Innovations", "Retail Trends", "Consumer Sentiment", "Financial Regulations", "Government Policies", "Technical Analysis", "Fundamental Analysis", "Cryptocurrency News", "Bitcoin", "Altcoins", "Cryptocurrency Regulations", "S&P 500", "Dow Jones", "NASDAQ", "Market Analysis", "Stock Market Indices" ]
|
81 |
+
|
82 |
+
# creating a data directory
|
83 |
+
# Define the directory path you want to create
|
84 |
+
directory_path = './data'
|
85 |
+
|
86 |
+
def call_functions(directory_path='./data'):
|
87 |
+
creating_data_dir(directory_path)
|
88 |
+
items = os.listdir(directory_path)
|
89 |
+
|
90 |
+
file_name = './combined_news_response.json'
|
91 |
+
|
92 |
+
if len(items) == 0:
|
93 |
+
print(f"Directory '{directory_path}' is empty.")
|
94 |
+
api = NewsDataApiClient(apikey=NEWSDATA_API_KEY)
|
95 |
+
retrieve_news_per_keyword(api,keywords)
|
96 |
+
combine_responses_into_one(directory_path)
|
97 |
+
convert_json_to_csv(file_name)
|
98 |
+
elif len(items) >= 2:
|
99 |
+
print(f"Directory '{directory_path}' contains at least two files.")
|
100 |
+
combine_responses_into_one(directory_path)
|
101 |
+
convert_json_to_csv(file_name)
|
102 |
+
else:
|
103 |
+
print(f"Directory '{directory_path}' contains only one file.")
|
104 |
+
|
105 |
+
# Read the combined CSV file and display the first few rows
|
106 |
+
csv_file_name = "combined_news_response.csv"
|
107 |
+
if os.path.exists(csv_file_name):
|
108 |
+
df = pd.read_csv(csv_file_name)
|
109 |
+
# Assuming df is your DataFrame
|
110 |
+
if 'Unnamed: 0' in df.columns:
|
111 |
+
df.drop('Unnamed: 0', axis=1, inplace=True)
|
112 |
+
first_few_rows = df.head(10) # Adjust the number of rows as needed
|
113 |
+
return first_few_rows
|
114 |
+
else:
|
115 |
+
return f"CSV file '{csv_file_name}' not found."
|
116 |
+
|
117 |
+
|
118 |
+
# Create a Gradio interface
|
119 |
+
iface = gr.Interface(
|
120 |
+
fn=call_functions,
|
121 |
+
inputs=gr.components.Textbox(label="Directory Path"),
|
122 |
+
outputs=gr.components.Dataframe(type="pandas")
|
123 |
+
)
|
124 |
+
|
125 |
+
|
126 |
+
# Launch the Gradio app
|
127 |
+
iface.launch(debug=True)
|
requirements.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
newsdataapi
|